在 C# 正则表达式中使用 \b 不起作用?
我想知道为什么以下正则表达式不匹配。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
引号不是单词字符,因此 \b 如果存在则不会匹配。引用前没有单词字符;因此,在引用之前,单词字符和非单词字符之间没有过渡。所以,没有匹配。
从您的评论中,您试图从字符串中删除单词字符。最直接的方法是将
\w
替换为空字符串: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:你期待一个空白。
它没有找到一个。
替换
为
,你就会明白我的意思。
you are expecting a whitespace.
it isn't finding one.
replace
with
and you'll see what i mean.