Using \b in C# regular expressions doesn't work?
-
20-09-2019 - |
Question
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?
Solution
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);
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow