Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET regex replace using backreference

Tags:

c#

regex

I have a fairly long string that contains sub strings with the following format:

project[1]/someword[1]
project[1]/someotherword[1]

There will be about 10 or so instances of this pattern in the string.

What I want to do is to be able to replace the second integer in square brackets with a different one. So the string would look like this for instance:

project[1]/someword[2]
project[1]/someotherword[2]

I''m thinking that regular expressions are what I need here. I came up with the regex:

project\[1\]/.*\[([0-9])\]

Which should capture the group [0-9] so I can replace it with something else. I'm looking at MSDN Regex.Replace() but I'm not seeing how to replace part of a string that is captured with a value of your choosing. Any advice on how to accomplish this would be appreciated. Thanks much.

*Edit: * After working with @Tharwen some I have changed my approach a bit. Here is the new code I am working with:

  String yourString = String yourString = @"<element w:xpath=""/project[1]/someword[1]""/> <anothernode></anothernode> <another element w:xpath=""/project[1]/someotherword[1]""/>";
 int yourNumber = 2;
 string anotherString = string.Empty;
 anotherString = Regex.Replace(yourString, @"(?<=project\[1\]/.*\[)\d(?=\]"")", yourNumber.ToString());
like image 399
TheMethod Avatar asked Nov 28 '22 17:11

TheMethod


1 Answers

Matched groups are replaced using the $1, $2 syntax as follows :-

csharp> Regex.Replace("Meaning of life is 42", @"([^\d]*)(\d+)", "$1($2)");
"Meaning of life is (42)"

If you are new to regular expressions in .NET I recommend http://www.ultrapico.com/Expresso.htm

Also http://www.regular-expressions.info/dotnet.html has some good stuff for quick reference.

like image 121
James Kyburz Avatar answered Dec 05 '22 17:12

James Kyburz