C# 带有替换简单字符串的正则表达式问题
我使用Regex替换,如下所示:C# 带有替换简单字符串的正则表达式问题,c#,.net,regex,C#,.net,Regex,我使用Regex替换,如下所示: string test = "[abc] Sends the employee mail. [twist] Sends the employee mail."; test = Regex.Replace(test, "[twist]", "hello"); 结果是: test = "[abc] Sendhello hellohe employee mahellol. [hellohellohellohellohello] Sendhello hellohe e
string test = "[abc] Sends the employee mail. [twist] Sends the employee mail.";
test = Regex.Replace(test, "[twist]", "hello");
结果是:
test = "[abc] Sendhello hellohe employee mahellol. [hellohellohellohellohello] Sendhello hellohe employee mahellol."
它应该在哪里用hello替换[twist]字符串。
这里出了什么问题。您必须避开括号(至少是开头的括号)。改变 到 或者,使用以避免双重
\
@"\[twist\]"
[twist]
被解释为t、w、i、s或t字符中的任何一个,它们都被hello
字符串替换。Regex.Replace(test,“\[twist\]”,“hello”)作为其他有用信息,您可以将[
转义为[[]
,因此
"[[]twist]"
或者你可以
"\\x5btwist]"
其中\x5b
是[
的ascii码。请注意,您需要转义\x5b
的
,否则“\x5b”==”[”
(C进行字符串替换)。通过转义,正则表达式“接收”\x5b
,并将其视为[
。显然,您可以使用@
@"\x5btwist]"
或者@“\[twist\]”
:-)尝试使用第一种方法之一。在大多数情况下会立即为您解释。:)
"\\x5btwist]"
@"\x5btwist]"