我正在尝试替换字符串中的模式,其中仅应替换标签之间的单词。需要替换的单词作为键和值对驻留在字典中。
目前这就是我正在尝试的:
string input = "<a>hello</a> <b>hello world</b> <c>I like apple</c>";
string pattern = (@"(?<=>)(.)?[^<>]*(?=</)");
Regex match = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = match.Matches(input);
var dictionary1 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
dictionary1.Add("hello", "Hi");
dictionary1.Add("world", "people");
dictionary1.Add("apple", "fruit");
string output = "";
output = match.Replace(input, replace => { return dictionary1.ContainsKey(replace.Value) ? dictionary1[replace.Value] : replace.Value; });
Console.WriteLine(output);
Console.ReadLine();
使用它,它确实会替换但仅替换第一个“hello”,而不替换第二个。我想替换标签之间出现的所有“hello”。
任何帮助将不胜感激。
最佳答案
问题是匹配是:
- 你好
- Hello World
- 我喜欢苹果
所以例如hello world
不在您的字典中。
根据您的代码,这可能是一个解决方案:
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var dictionary1 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
dictionary1.Add("hello", "Hi");
dictionary1.Add("world", "people");
dictionary1.Add("apple", "fruit");
string input = "<a>hello</a> <b>hello world</b> <c>I like apple</c>";
string pattern = ("(?<=>)(.)?[^<>]list|" + GetKeyList(dictionary1) + "(?=</)");
Regex match = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = match.Matches(input);
string output = "";
output = match.Replace(input, replace => {
Console.WriteLine(" - " + replace.Value);
return dictionary1.ContainsKey(replace.Value) ? dictionary1[replace.Value] : replace.Value;
});
Console.WriteLine(output);
}
private static string GetKeyList(Dictionary<string, string> list)
{
return string.Join("|", new List<string>(list.Keys).ToArray());
}
}
fiddle :https://dotnetfiddle.net/zNkEDv
如果有人想深入研究这个问题,请告诉我为什么需要“列表|”在列表中(因为第一项被忽略),我将不胜感激。
关于C# 使用字典替换正则表达式匹配的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44311565/