我有一个相当长的字符串,其中包含以下格式的子字符串:
project[1]/someword[1]
project[1]/someotherword[1]
这个模式在字符串中大约会出现10次左右。
我想做的是能够用不同的整数替换方括号中的第二个整数。例如,字符串将会像下面这样:
project[1]/someword[2]
project[1]/someotherword[2]
我认为正则表达式是我在这里需要的东西。我想到了以下正则表达式:
project\[1\]/.*\[([0-9])\]
我想要捕获[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());