tags:

views:

80

answers:

2

What is the regex syntax to use part of a matched expression in the subsequent part of the search?

So, for example, if I have:
"{marker=1}some text{/marker=1}"
or
"{marker=2}some text{/marker=2}"

I want to use the first digit found in the pattern to find the second digit. So in
"{marker=1}{marker=2}some text{/marker=2}{/marker=1}"
the regex would match the 1's and then the 2's.

So far I've come up with {marker=(\d)}(.*?){/marker=(\d)} but don't know how to specify the second \d to refer to the value found in the first \d.

I'm doing this in C#.

+1  A: 

Numbered backreference is just \n, so \1 should work here:

Regex re = new Regex(@"\{marker=(\d)\}(.*?)\{/marker=(\1)\}");
// expect to work
Console.WriteLine(re.IsMatch(@"{marker=1}some text{/marker=1}"));
// expect to fail (end marker is different)
Console.WriteLine(re.IsMatch(@"{marker=1}some text{/marker=2}"));
Marc Gravell
+1  A: 

try: {marker=(\d)}(.*?){/marker=(\1)}

Erich