简体   繁体   English

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

[英]Replace multiple Regex Matches each with a different replacement

I have a string that may or may not have multiple matches for a designated pattern. 我有一个字符串,可能有或没有指定模式的多个匹配。

Each needs to be replaced. 每个都需要更换。

I have this code: 我有这个代码:

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();

The problem is that when I have several matches the first is replaced and the starting index of the other is changed so that in some cases after the replacement when the string is shorten I get an index out of bounds.. 问题是,当我有几个匹配时,第一个被替换,另一个的起始索引被改变,所以在某些情况下,当字符串缩短时,我得到一个超出范围的索引。

I know I could just use Regex.Replace for each match but this sound performance heavy and wanted to see if someone could point a different solution to substitute multiple matches each with a different string. 我知道我可以为每场比赛使用Regex.Replace ,但这个声音表现很重,并希望看看是否有人可以指出一个不同的解决方案,用不同的字符串替换多个匹配。

Use a Match evaluator inside the Regex.Replace : Regex.Replace使用Match评估器:

var pattern = @"\$\$\@[a-zA-Z0-9_]*\b";
var stringVariableMatches = Regex.Replace(strValue, pattern, 
        m => variablesDictionary[m.Value]);

The Regex.Replace method will perform global replacements, ie will search for all non-overlapping substrings that match the indicated pattern, and will replace each found match value with the variablesDictionary[m.Value] . Regex.Replace方法将执行全局替换,即将搜索与指示模式匹配的所有非重叠子串,并将使用variablesDictionary[m.Value]替换每个找到的匹配值。

Note that it might be a good idea to check if the key exists in the dictionary . 请注意, 检查字典中是否存在密钥可能是个好主意。

See a C# demo : 查看C#演示

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);
    }
}

Output: $$@Unknown and Value . 输出: $$@Unknown and Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM