【问题标题】:How to replace Match value with other value in Regex如何用正则表达式中的其他值替换匹配值
【发布时间】:2015-04-23 09:17:16
【问题描述】:

我有字符串string testString = "Test id=10 sgdsdg id=15" 我想将 10 替换为 100 和 15 替换为 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");
    }
}

我不想使用跟随,因为对于每场比赛我都必须检查一些情况。喜欢身份证 Match.Value =10 Match.Value =12

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

【问题讨论】:

  • Regex.Replace(yourString, @"(?&lt;=id=)(\d+)", "$10");
  • 但它会将 10 和 15 替换为相同的 10 美元,你认为这里的 10 美元是什么?
  • $1 将引用正则表达式中的第一个组,对于第一个匹配项,它将返回 10。正则表达式引擎将再次尝试匹配字符串,并且第二次返回15,它将再次存储在$1 中。问题是执行$10 将指示正则表达式引擎检查不存在的第10 个匹配组。我在下面提出了解决此问题的方法。
  • 能否请您写下整个代码。我试过了,但它不起作用。

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


【解决方案1】:

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

要解决这个问题,只需使用 named 组,如下所示:

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 链接。

【讨论】:

  • 100 和 150 只是一个例子。我想做很多检查。这就是我想使用开关盒的原因。
  • @HemantMalpote:只要该模式适用:id=&lt;somedigit(s)&gt;,那么表达式仍然成立。
  • 我想你得到了我想要的。我必须为匹配集合中的不同匹配执行大量操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
相关资源
最近更新 更多