Regex replace / search uses values ββ/ variables in search text
What is the regular expression syntax for using a matched expression part in a subsequent search part?
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 will match 1 and then 2.
So far I have come up with {marker = (\ d)} (. *?) {/ Marker = (\ d)}, but I don't know how to specify the second \ d to refer to the value found in the first \ d.
I am doing this in C #.
+2
source to share
2 answers
A numbered backlink 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}"));
+1
source to share