C# 使用字典替换正则表达式匹配的模式

标签 c# .net regex

我正在尝试替换字符串中的模式,其中仅应替换标签之间的单词。需要替换的单词作为键和值对驻留在字典中。

目前这就是我正在尝试的:

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/

相关文章:

regex - 如何在R中的list.files中执行复杂的正则表达式

c# - VS2015社区中的单元测试异常

c# - SQL 搜索多个列的多个值列表

.net - Memcached 1 兆限制,Enyim .Net 客户端

java - 通过正则表达式搜索和替换文本段落中的管道分隔字符

javascript - 用一个替换多个连续的连字符

c# - 从文件夹中删除文件的单元测试方法

c# - 事件支持 WP 8.1

c# - 如何在 C# .NET 中反序列化复杂的 JSON 对象?

c# - 检查进程状态