使用.NET Regex.Replace()多次替换表达式

时间:2016-04-15 05:30:44

标签: c# .net regex replace

我似乎找不到这个问题的匹配,所以如果它是重复的话我会提前道歉。

给出模板:<<FirstName>> << FirstName >>

我想使用一个应该匹配两者的正则表达式替换'<<>>'之间的两个字符串。

以下代码似乎没有按照我预期的方式运作:

[Test]
public void ShouldReplaceMultiple()
{
  var pattern = "<<.*FirstName.*>>";
  var template = "<<FirstName>> <<FirstName>>";
  var replaceWith = "FOO";

  var regex = new Regex(pattern); 

  Assert.AreEqual("FOO FOO", regex.Replace(template, replaceWith));
}

测试结果如下:

Expected string length 7 but was 3. Strings differ at index 3.
  Expected: "FOO FOO"
  But was:  "FOO"
  --------------^

我不明白为什么两根琴弦都不会被替换?

2 个答案:

答案 0 :(得分:3)

使用.*?

让它变得非贪婪
var pattern = "<<.*?FirstName.*?>>";
var template = "<<FirstName>> <<FirstName>>";
var replaceWith = "FOO";

var regex = new Regex(pattern); 

Console.WriteLine(regex.Replace(template, replaceWith));

<强> Ideone Demo

如果您只想在spaces之间处理<<>>,那么这就足够了

<<\s*?FirstName\s*?>>

答案 1 :(得分:1)

string pattern = @"<<(?<=<<)\s*FirstName\s*(?=>>)>>";
var template = "<<FirstName>> <<FirstName>>";
var replaceWith = "FOO";

var regex = new Regex(pattern); 

Assert.AreEqual("FOO FOO", regex.Replace(template, replaceWith));