C # Regex replace with backreference

I have a rather long string containing substrings with the following format:

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

The line will contain about 10 instances of this template.

I want to do to replace the second integer in square brackets with another. So the line will look like this:

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

I think regular expressions are what I need here. I came up with a regex:

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

To do this, you need to capture the group [0-9], so that I can replace it with something else. I look at MSDN Regex.Replace (), but I don’t see how to replace the part of the string that is captured with the value of your choice. Any advice on how to do this would be appreciated. Thank you very much.

* Edit: * After working with @Tharwen, I changed my approach a bit. Here is the new code I'm 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()); 
+4
source share
4 answers

I adapted yours to use lookbehind and lookahead to match only the digit preceded by "project [1] / xxxxx [', and then"] ":

 (?<=project\[1\]/.*\[)\d(?=\]") 

Then you can use:

 String yourString = "project[1]/someword[1]"; int yourNumber = 2; yourString = Regex.Replace(yourString, @"(?<=project\[1\]/.*\[)\d(?=\]"")", yourNumber.ToString()); 

I think maybe you were confused because Regex.Replace has a lot of overloads that are slightly different from each other. I used this one .

+2
source

The corresponding groups are replaced with the syntax $ 1, $ 2 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 contains some useful quick reference materials.

+23
source

If you want to process the value of the captured group before replacing it, you will have to separate the different parts of the line, make changes and put them together.

 string test = "project[1]/someword[1]\nproject[1]/someotherword[1]\n"; string result = string.Empty; foreach (Match match in Regex.Matches(test, @"(project\[1\]/.*\[)([0-9])(\]\n)")) { result += match.Groups[1].Value; result += (int.Parse(match.Groups[2].Value) + 1).ToString(); result += match.Groups[3].Value; } 

If you just want to replace the text verbatim, it's easier: Regex.Replace(test, @"abc(.*)cba", @"cba$1abc") .

0
source

you can use String.Replace (String, String) for example

 String.Replace ("someword[1]", "someword[2]") 
-3
source

All Articles