使用反向引用替换C#Regex

The*_*hod 4 c# regex

我有一个相当长的字符串,其中包含具有以下格式的子字符串:

project[1]/someword[1]
project[1]/someotherword[1]
Run Code Online (Sandbox Code Playgroud)

字符串中将有大约10个左右的此模式实例.

我想要做的是能够用方括号替换另一个整数.所以字符串看起来像这样:

project[1]/someword[2]
project[1]/someotherword[2]
Run Code Online (Sandbox Code Playgroud)

我在想这里正则表达式是我需要的.我想出了正则表达式:

project\[1\]/.*\[([0-9])\]
Run Code Online (Sandbox Code Playgroud)

哪个应该捕获组[0-9]所以我可以用其他东西替换它.我正在看MSDN Regex.Replace(),但我没有看到如何用您选择的值替换捕获的字符串的一部分.任何关于如何实现这一点的建议将不胜感激.非常感谢.

*编辑:*在与@Tharwen合作之后,我改变了一些方法.这是我正在使用的新代码:

  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());
Run Code Online (Sandbox Code Playgroud)

Jam*_*urz 27

使用$ 1,$ 2语法替换匹配的组,如下所示: -

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

如果您不熟悉.NET中的正则表达式,请推荐http://www.ultrapico.com/Expresso.htm

另外http://www.regular-expressions.info/dotnet.html有一些好的东西可供快速参考.


Tha*_*wen 2

我已经对您进行了调整,以使用后视和前视来仅匹配前面为“project[1]/xxxxx[”、后跟“]”的数字:

(?<=project\[1\]/.*\[)\d(?=\]")
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用:

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

我想您可能会感到困惑,因为 Regex.Replace 有很多重载,它们的作用略有不同。我用过这个