0

I couldn't seem to find a match for this question so my apologies in advance if it's a duplicate.

Given the template: <<FirstName>> << FirstName >>

I want to replace both strings between the '<<>>''s using a single regex that should match both.

The following code doesn't seem to work the way I'm expecting:

[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));
}

The output of the test is as follows:

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

I don't understand why both strings won't be replaced?

mekuls
  • 101
  • 1
  • 4

2 Answers2

3

Make it non-greedy using .*?

var pattern = "<<.*?FirstName.*?>>";
var template = "<<FirstName>> <<FirstName>>";
var replaceWith = "FOO";

var regex = new Regex(pattern); 

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

Ideone Demo

If you want to deal only with spaces in between the <<>>, then this will suffice

<<\s*?FirstName\s*?>>
rock321987
  • 10,942
  • 1
  • 30
  • 43
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));
M.S.
  • 4,283
  • 1
  • 19
  • 42