【问题标题】:How to replace Match value with new value in Regex如何在正则表达式中用新值替换匹配值
【发布时间】:2015-04-01 08:44:04
【问题描述】:

我有一个字符串,像这样:

string str = "id=1,id=2,id=5,id=22";

然后,我在这个字符串上应用一些正则表达式,以获取标识符:

var idMatchCollection = regex.Matches(str);

foreach(Match match in idMatchCollection)
{
   var newValue = SomeFunction(match.toString()); 
  // i want to replace newValue for Match which we have in foreach with newValue. That reflect in sting str.
}

所以,最终的输出应该是这样的:

str = "id=234,id=576,id=5767,id=756765"

(234,567,5767,756765)是我在foreach循环for(1,2,5,22)中通过函数得到的值

【问题讨论】:

  • 您是否有一个Dictionary<string, string>,其键与ids 匹配,可用于执行替换?
  • 我不明白......输入看起来如何,输出应该看起来如何?
  • 我不想使用字典。我想要一些不同的方法来替换每场比赛。

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


【解决方案1】:

您可能希望使用 Regex.Replace(String, MatchEvaluator) 方法,该方法在每次匹配时调用您的回调函数。

这是来自MSDN 的示例:

using System;
using System.Text.RegularExpressions;

class RegExSample
{
    static string CapText(Match m)
    {
        // Get the matched string. 
        string x = m.ToString();
        // If the first char is lower case... 
        if (char.IsLower(x[0]))
        {
            // Capitalize it. 
            return char.ToUpper(x[0]) + x.Substring(1, x.Length - 1);
        }
        return x;
    }

    static void Main()
    {
        string text = "four score and seven years ago";

        System.Console.WriteLine("text=[" + text + "]");

        Regex rx = new Regex(@"\w+");

        string result = rx.Replace(text, new MatchEvaluator(RegExSample.CapText));

        System.Console.WriteLine("result=[" + result + "]");
    }
}

【讨论】:

    【解决方案2】:

    您正在寻找Regex.Replace 方法。喜欢:

    string str = "id=1,id=2,id=5,id=22";
    var regex = new Regex("[0-9]+");
    var replaced = regex.Replace(str, (match) =>
    {
      return "x" + match.Value + "x";
    });
    // replaced will have value of "id=x1x,id=x2x,id=x5x,id=x22x"
    

    【讨论】:

      【解决方案3】:

      我只能想到这个:

      var regex = new Regex(@"(?<=id\=)\d+");
      var str = "id=1,id=2,id=5,id=22";
      var coll = new List<string>();
      coll.AddRange(new string[] { "234", "567", "5767", "756765" });
      var cnt = 0;
      var prev_idx = 0;
      var output = string.Empty;
      for (var match = regex.Match(str); match.Success; match = match.NextMatch())
      {
          output += str.Substring(prev_idx, match.Index - prev_idx) + coll[cnt++];
          prev_idx = match.Index + match.Length;
      }
      // Output: id=234,id=567,id=5767,id=756765 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-19
        • 1970-01-01
        • 2016-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-16
        相关资源
        最近更新 更多