使用不同的替换替换多个正则表达式匹配

时间:2016-05-11 09:07:56

标签: c# regex

我有一个字符串,可能有也可能没有指定模式的多个匹配。

每个都需要更换。

我有这段代码:

var pattern = @"\$\$\@[a-zA-Z0-9_]*\b";
var stringVariableMatches = Regex.Matches(strValue, pattern);
var sb = new StringBuilder(strValue);

foreach (Match stringVarMatch in stringVariableMatches)
{
    var stringReplacment = variablesDictionary[stringVarMatch.Value];
    sb.Remove(stringVarMatch.Index, stringVarMatch.Length)
            .Insert(stringVarMatch.Index, stringReplacment);
}

return sb.ToString();

问题在于,当我有多个匹配时,第一个匹配并且另一个的起始索引被更改,以便在某些情况下在替换后字符串缩短时,我得到一个超出范围的索引..

我知道我可以为每场比赛使用Regex.Replace,但这个声音表现很重,并希望看到有人能指出一个不同的解决方案,用不同的字符串替换多个匹配。

1 个答案:

答案 0 :(得分:10)

Regex.Replace

中使用匹配评估程序
var pattern = @"\$\$\@[a-zA-Z0-9_]*\b";
var stringVariableMatches = Regex.Replace(strValue, pattern, 
        m => variablesDictionary[m.Value]);

Regex.Replace方法将执行全局替换,即将搜索与指示模式匹配的所有非重叠子字符串,并将{{1}替换每个找到的匹配值}。

请注意check if the key exists in the dictionary可能是个好主意。

查看C# demo

variablesDictionary[m.Value]

输出:using System; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var variablesDictionary = new Dictionary<string, string>(); variablesDictionary.Add("$$@Key", "Value"); var pattern = @"\$\$@[a-zA-Z0-9_]+\b"; var stringVariableMatches = Regex.Replace("$$@Unknown and $$@Key", pattern, m => variablesDictionary.ContainsKey(m.Value) ? variablesDictionary[m.Value] : m.Value); Console.WriteLine(stringVariableMatches); } }

相关问题