2012-01-03 87 views
2

当我打电话替换在C#中的所有功能的特殊字符

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

这给我下面的结果我不知道为什么它是给人意想不到的结果。

我[NewTextNewTextNewTextNewTextNewTextNewTextNewText] tNewTextxt NewTextnd NewTextnothNewTextNewText [NewTextNewTextNewTextNewTextNewTextNewTextNewText]

我怎样才能改变这样的正则表达式的结果可能是这样的。

我NewText文字和另一NewText

+6

为什么不只是使用String。如果您没有使用RegEx的功能,请更换?如果它是不区分大小写的替换你需要的,请参阅http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx – hatchet 2012-01-03 20:02:10

+0

Accepte答案,如果它适合你 – 2012-01-04 14:23:02

回答

5

[]在RegEx中有特殊含义;它可以让你指定一个匹配字符/字符类的'列表'。你需要逃避它,使其工作像您期望:

"\\[Replace\\]" 

双回斜线在这里使用,因为首先是要逃避C#的斜线,那么第二个逃脱它的正则表达式。

这是当前的正则表达式基本上是这样做的:匹配其中任意字符:R, e, p, l, a, c, e

这就是为什么你看到你的NewText重复7次,背到后面,方括号在开始你的结果文本。也就是用NewText简单地替换这7个字符中的任何一个。

转义[]消除了特殊的含义,因此您可以直接匹配,也可以完全匹配您希望匹配的内容。

+0

我也会回应评论/回答的效果,在这种情况下,简单的'String.Replace()'会更简单。当你有这样简单而又简单的替换时,使用它更容易,没有可变模式匹配。 – 2012-01-03 20:09:05

2

其更好地利用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); 
1

那是因为你与你的替换文本替换字符集的每一次出现。改变你的电话:

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

它应该像你期望的那样工作。但是正则表达式很复杂,所以一个简单的“string.Replace”会更适合你!

+0

你需要用@作为你的匹配文本的前缀,你需要转义\ for C# – 2012-01-03 20:17:40

+1

@AnthonyShaw:你是对的,我已经改变了样本。谢谢! – Fischermaen 2012-01-03 20:32:13

1

我想你想要这个:

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

这样一来,[替换]作为文字处理。

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

这是告诉替换通过使用()并替换'['替换']'找到一个匹配并交换出替换文本。