Using \b in C# regular expressions doesn't work?
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\""));
stri开发者_如何学Cng 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?
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);
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.
精彩评论