如何将匹配值替换为正则表达式中的其他值

时间:2015-04-23 09:17:16

标签: c# asp.net regex asp.net-mvc c#-4.0

我有字符串string testString = "Test id=10 sgdsdg id=15" 我想用10和100替换10和150 我写了

string testString = "Test id=10 sgdsdg id=15";

Regex testregex = new Regex("(?<=id=)\\d+");

MatchCollection matchCollection = testregex.Matches(testString);

foreach (Match match in matchCollection)
{
    if (match.Value.Equals("10"))
    {
        match.Result("100");
    }

    if (match.Value.Equals("15"))
    {
        match.Result("150");
    }
}

我不想使用以下内容,因为我必须检查一些案例。喜欢id Match.Value =10 Match.Value =12

testregex .Replace(testString , m => oldNewValueMapping[m.Value])

1 个答案:

答案 0 :(得分:1)

替换为$10会有一个小问题,因为.NET引擎会查找第10组。

要解决此问题,只需使用命名的组,如下所示:

string testString = "Test id=10 sgdsdg id=15";
Console.WriteLine(Regex.Replace(testString, @"(?<=id=)(?<digit>\d+)", "${digit}0"));

收率:

Test id=100 sgdsdg id=150

有关名称组的详情,请参阅this链接。