Regex.Replace, why \ b prevents this?

Why does the second statement not work?

work

Regex.Replace("zz WHERE zz", "where", "yy", RegexOptions.IgnoreCase | RegexOptions.Singleline); 

not

 Regex.Replace("zz WHERE zz", "\bwhere\b", "yy", RegexOptions.IgnoreCase | RegexOptions.Singleline); 

This works, but replaces the space I don't want to do

 Regex.Replace("zz WHERE zz", " where ", "yy", RegexOptions.IgnoreCase | RegexOptions.Singleline); 
+4
source share
2 answers

Because \b is a backspace control character (U + 0008). Backslashes themselves do not even get into regular expression there.

To use it for its intended purpose in a regular expression, you need to either escape twice (output a backslash for a C # line so that they are a normal backslash for a regular expression):

 "\\bwhere\\b" 

or use a string literal:

 @"\bwhere\b" 
+7
source

You need to avoid backslashes in C # or use the @ text literal:

 @"\bwhere\b" 
+2
source

Source: https://habr.com/ru/post/1310285/


All Articles