在 C# 正则表达式中使用 \b 不起作用?

发布于 2024-08-25 04:54:35 字数 313 浏览 2 评论 0原文

我想知道为什么以下正则表达式不匹配。

string query = "\"1 2\" 3";
string pattern = string.Format(@"\b{0}\b", Regex.Escape("\"1 2\""));
string repl = Regex.Replace(query, pattern, "", RegexOptions.CultureInvariant);

请注意,如果我从 pattern 中删除单词边界字符 (\b),它会很好地匹配。 '\b' 是否有什么东西可能会导致这个问题?

I am wondering why the following regex does not match.

string query = "\"1 2\" 3";
string pattern = string.Format(@"\b{0}\b", Regex.Escape("\"1 2\""));
string repl = Regex.Replace(query, pattern, "", RegexOptions.CultureInvariant);

Note that if I remove the word boundary characters (\b) from pattern, it matches fine. Is there something about '\b' that might be tripping this up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤城病女 2024-09-01 04:54:35

引号不是单词字符,因此 \b 如果存在则不会匹配。引用前没有单词字符;因此,在引用之前,单词字符和非单词字符之间没有过渡。所以,没有匹配。

从您的评论中,您试图从字符串中删除单词字符。最直接的方法是将 \w 替换为空字符串:

string repl = Regex.Replace(query, "\w", "", RegexOptions.CultureInvariant);

A quote is not a word character, so \b will not be a match if it is there. There is no word character before the quote; so, before the quote, there is no transition between word characters and non-word characters. So, no match.

From your comment you are trying to remove word characters from a string. The most straightforward way to do that would be to replace \w with an empty string:

string repl = Regex.Replace(query, "\w", "", RegexOptions.CultureInvariant);
耶耶耶 2024-09-01 04:54:35

你期待一个空白。
它没有找到一个。
替换

string query = "\"1 2\" 3";

string query = "\" 1 2 \" 3";

,你就会明白我的意思。

you are expecting a whitespace.
it isn't finding one.
replace

string query = "\"1 2\" 3";

with

string query = "\" 1 2 \" 3";

and you'll see what i mean.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文