用特殊字符替换C#中的所有函数

本文关键字:函数 特殊字符 替换 | 更新日期: 2023-09-27 18:19:32

当我调用时

Regex.Replace(
    "My [Replace] text and another [Replace]", 
    "[Replace]", 
    "NewText", 
    RegexOptions.IgnoreCase)

这给了我以下的结果我不知道为什么它会给我意想不到的结果。

我的新文本

我怎样才能改变Regex,结果会是这样。

我的NewText文本和另一个NewText

用特殊字符替换C#中的所有函数

[]在RegEx中具有特殊意义;它允许您为匹配指定字符/字符类的"列表"。你需要逃离它,让它像你期望的那样工作:

"''[Replace'']"

这里使用双反斜杠,因为第一个用于转义C#的斜杠,第二个用于转义Regex的斜杠。

这就是您当前regex的基本功能:匹配其中的任何字符:R, e, p, l, a, c, e

这就是为什么您看到NewText在结果文本开头的方括号之间背靠背重复了7次。然后,它还简单地用NewText替换这7个字符中的任何一个。

跳过[]可以去除特殊含义,因此您可以从字面上匹配,并且完全匹配您想要匹配的内容。

最好使用String.Replace而不是正则表达式。。。。。。。。。。。

string errString = "This docment uses 3 other docments to docment the docmentation";
        Console.WriteLine("The original string is:{0}'{1}'{0}", Environment.NewLine, errString);
        // Correct the spelling of "document".
        string correctString = errString.Replace("docment", "document");
        Console.WriteLine("After correcting the string, the result is:{0}'{1}'",
                Environment.NewLine, correctString);

我想你想要这个:

Regex.Replace(
  @"My [Replace] text and another [Replace]", 
  @"'[Replace']", 
  "NewText", 
  RegexOptions.IgnoreCase)

这样,[Replace]就被视为文字。

这是因为您要用替换文本替换一组字符的每次出现。将您的呼叫更改为:

Regex.Replace(
    "My [Replace] text and another [Replace]", 
    @"'[Replace']", 
    "NewText", 
    RegexOptions.IgnoreCase)

它应该像你期望的那样工作。但Regex在某种程度上很复杂,所以一个简单的"string.Replace"会更适合你!

[]是正则表达式字符组运算符。它匹配组中的任何字符。

如果你想真正匹配[Replace],你必须用反斜杠'转义方括号。

Regex.Replace(text, @"('[Replace'])", replacementText);

这是告诉replace使用()查找匹配项,并替换"["replace"]",然后用替换文本替换它。