如何在正则表达式中将匹配值替换为新值

时间:2015-04-01 08:44:04

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

我有一个字符串,如下:

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)

中通过函数获得的值

3 个答案:

答案 0 :(得分:2)

您可能希望使用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 + "]");
    }
}

答案 1 :(得分:0)

您正在寻找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"

答案 2 :(得分:0)

我只能达到这个目的:

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 
相关问题