我有一个字符串,可能有或没有指定模式的多个匹配.
每个都需要更换.
我有这个代码:
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();
Run Code Online (Sandbox Code Playgroud)
问题是,当我有几个匹配时,第一个被替换,另一个的起始索引被改变,所以在某些情况下,当字符串缩短时,我得到一个超出范围的索引.
我知道我可以只Regex.Replace
为每场比赛使用,但这个声音性能很重,想看看是否有人可以指出一个不同的解决方案,用不同的字符串替换多个匹配.
Wik*_*żew 11
在以下内容中使用匹配评估程序Regex.Replace
:
var pattern = @"\$\$\@[a-zA-Z0-9_]*\b";
var stringVariableMatches = Regex.Replace(strValue, pattern,
m => variablesDictionary[m.Value]);
Run Code Online (Sandbox Code Playgroud)
该Regex.Replace
方法将执行全局替换,即将搜索与指示的模式匹配的所有非重叠子串,并将用该替换每个找到的匹配值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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:$$@Unknown and Value
.
归档时间: |
|
查看次数: |
4571 次 |
最近记录: |