繁体   English   中英

使用反向引用替换C#Regex

[英]C# Regex replace using backreference

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

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());

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

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

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

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

我已经改编你的使用lookbehind和lookahead只匹配一个数字,前面是'project [1] / xxxxx ['后跟']':

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

然后,您可以使用:

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

我想也许你感到困惑,因为Regex.Replace有很多重载,它们做的事情略有不同。 我用过这个

如果要在替换之前处理捕获组的值,则必须将字符串的不同部分分开,进行修改并将它们重新组合在一起。

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;
}

如果您只想逐字替换文本, Regex.Replace(test, @"abc(.*)cba", @"cba$1abc")容易: Regex.Replace(test, @"abc(.*)cba", @"cba$1abc")

例如,您可以使用String.Replace(String,String)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM