user34537
user34537

Reputation:

Regex.Replace why does \b prevent this?

Why does the second statement fail?

works

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

does not

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

This works to but replaces the space which i do not want to do

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

Upvotes: 5

Views: 83

Answers (2)

Joey
Joey

Reputation: 354576

Because \b is the backspace control character (U+0008). The backslashes themselves there don't even get to the regular expression.

To use it as intended in a regular expression you need to either double-escape (escape the backslashes for C#'s string so they are normal backslashes for the regex):

"\\bwhere\\b"

or use a verbatim string literal:

@"\bwhere\b"

Upvotes: 7

Mark Byers
Mark Byers

Reputation: 838336

You need to escape the backslashes in C#, or else use a verbatim string literal @:

@"\bwhere\b"

Upvotes: 2

Related Questions