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);
2 个解决方案
#1
7
Because \b
is the backspace control character (U+0008). The backslashes themselves there don't even get to the regular expression.
因为\ b是退格控制字符(U + 0008)。那里的反斜杠本身甚至没有达到正则表达式。
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):
要在正则表达式中按预期使用它,您需要双重转义(转义C#的字符串的反斜杠,以便它们是正则表达式的正常反斜杠):
"\\bwhere\\b"
or use a verbatim string literal:
或使用逐字字符串文字:
@"\bwhere\b"
#2
2
You need to escape the backslashes in C#, or else use a verbatim string literal @
:
你需要在C#中转义反斜杠,否则使用逐字字符串文字@:
@"\bwhere\b"
#1
7
Because \b
is the backspace control character (U+0008). The backslashes themselves there don't even get to the regular expression.
因为\ b是退格控制字符(U + 0008)。那里的反斜杠本身甚至没有达到正则表达式。
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):
要在正则表达式中按预期使用它,您需要双重转义(转义C#的字符串的反斜杠,以便它们是正则表达式的正常反斜杠):
"\\bwhere\\b"
or use a verbatim string literal:
或使用逐字字符串文字:
@"\bwhere\b"
#2
2
You need to escape the backslashes in C#, or else use a verbatim string literal @
:
你需要在C#中转义反斜杠,否则使用逐字字符串文字@:
@"\bwhere\b"