将多个正则表达式匹配项替换为不同的替换项 [英] Replace multiple Regex Matches each with a different replacement

查看:61
本文介绍了将多个正则表达式匹配项替换为不同的替换项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,该字符串可能与指定模式的多个匹配项匹配,也可能不与之匹配.

I have a string that may or may not have multiple matches for a designated pattern.

每个都需要更换.

我有此代码:

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..

我知道我只能为每个匹配项使用 Regex.Replace ,但是这种声音表现很沉重,我想看看是否有人可以指出不同的解决方案,以多个匹配项替换为不同的字符串.

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 内使用Match评估程序:

Use a Match evaluator inside the Regex.Replace:

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

Regex.Replace 方法将执行 global 替换,即搜索与指定模式匹配的所有不重叠子字符串,并将每个找到的匹配值替换为 variablesDictionary [m.Value] .

The Regex.Replace method will perform global replacements, i.e. will search for all non-overlapping substrings that match the indicated pattern, and will replace each found match value with the variablesDictionary[m.Value].

请注意,参见 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);
    }
}

输出: $$ @ Unknown and Value .

这篇关于将多个正则表达式匹配项替换为不同的替换项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆