简体   繁体   English

Regex.Replace 不起作用

[英]Regex.Replace not working

I am having a strange issue with Regex.Replace我在 Regex.Replace 上遇到了一个奇怪的问题

string test = "if the other party is in material breach of such contract and, after <span style=\"background-color:#ffff00;\">forty-five (45)</span> calendar days notice of such breach";
string final = Regex.Replace(test, "forty-five (45)", "forty-five (46)", RegexOptions.IgnoreCase);

the "final" string still shows "forty-five (45)". “最终”字符串仍显示“四十五 (45)”。 Any idea why?知道为什么吗? I am assuming it has to do something with the tag.我假设它必须对标签做一些事情。 How do I fix this?我该如何解决?

Thanks谢谢

Escape the parenthesis.转义括号。 Depending on the language, might require two back slashes.根据语言,可能需要两个反斜杠。

string final = Regex.Replace(test, "forty-five \(45\)", "forty-five (46)", RegexOptions.IgnoreCase);

Basically, parenthesis are defined to mean something, and by escaping the characters, you are telling regex to use the parenthesis character, and not the meaning.基本上,括号被定义为表示某些东西,通过转义字符,您告诉正则表达式使用括​​号字符,而不是含义。

Better yet, why are you using a Regex to do this at all?更好的是,您为什么要使用正则表达式来执行此操作? Try just doing a normal string replacement .尝试做一个普通的字符串替换

string final = test.Replace("forty-five (45)", "forty-six (46)")

Parentheses are special in regular expressions.括号在正则表达式中很特殊。 They delimit a group , to allow for things such as alternation.它们划定一个,以允许诸如交替之类的事情。 For example, the regular expression foo(bar|bat)baz matches:例如,正则表达式foo(bar|bat)baz匹配:

  • foo , followed by foo ,然后是
  • either bar OR bat , followed by要么bar要么bat ,然后是
  • baz

So, a regular expression like foo(bar) will never match the literal string foo(bar) .因此,像foo(bar)这样的正则表达式永远不会匹配文字字符串foo(bar) What it will match is the literal string foobar .它将匹配的是文字字符串foobar Consequently, you need to escape the metacharacters.因此,您需要转义元字符。 In C#, this should do you:在 C# 中,你应该这样做:

string final = Regex.Replace(test, @"forty-five \(45\)", "forty-five (46)", RegexOptions.IgnoreCase);

The @-quoted string helps avoid headaches from excessive backslashes. @-quoted 字符串有助于避免过多反斜杠引起的麻烦。 Without it, you'd have to write "forty-five \\(45\\)".没有它,你必须写“四十五\\(45\\)”。

如果您无法转义括号,请将它们放在字符类中:

forty-five [(]45[)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM