c# - 用不同的替换替换多个正则表达式匹配

标签 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,但这种声音性能很重,想看看是否有人可以指出不同的解决方案来用不同的字符串替换多个匹配。

最佳答案

Regex.Replace 中使用 Match 求值器:

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

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

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

查看 C# demo :

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 和 Value

关于c# - 用不同的替换替换多个正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37157907/

相关文章:

c# - 读/写字符串二进制数据 - BinaryReader

c# - Visual Studio 2013 数据库创建错误 : a network related or instance specific error occurred while establishing connection with sqlserver

c# - ASP.NET 正则表达式验证器未按预期进行验证

c# - UWP AdControl 无法正常工作

c# - 使用 Azure Active Directory 配置 URL 重定向

c# - GridView 从抛出异常背后的代码更新

sql - 在某个单词 Presto SQL 之后提取字符串

javascript - 替换第二组 [ 和 ] 之间的字符串

python - re.search 在 MSYS2 下运行(并读取文件)时令人惊讶地以 None 结束?

javascript - 使用 ng-pattern 禁用 angularjs 中的按钮