【问题标题】:iterating over a dictionary of Regex in C#在 C# 中迭代​​正则表达式字典
【发布时间】:2015-09-24 00:05:17
【问题描述】:

我有一个函数可以查找并替换输入字符串text的正则表达式

    public static string Replacements(string text)
    {

        string output = Regex.Replace(text, @"\b[a-zA-Z0-9.-_]+@[a-z][A-Z0-9.-]+\.[a-zA-Z0-9.-]+\b","email");

        return output;
    }

假设我想将替换正则表达式放入字典中

    static Dictionary<string, string> dict1 = new Dictionary<string, string>
    {
        {@"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$", "phoneno"},
        {@"\b[a-zA-Z0-9.-_]+@[a-z][A-Z0-9.-]+\.[a-zA-Z0-9.-]+\b","email"},

    };

我想遍历字典来替换文本。我该怎么做?我在这里尝试了使用 forloop 的解决方案:What is the best way to iterate over a Dictionary in C#?

    public static string Replacements(string text)
    {

        string output = text;
        foreach (KeyValuePair<string, string> item in dict1)
        {
            output = Regex.Replace(text, item.Key, item.Value);
        }


        return output;
    }

但它没有工作。有一个更好的方法吗?我得到一个参数异常是未处理的错误:

parsing "^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$" - Quantifier {x,y} following nothing.

【问题讨论】:

  • 您需要将output 而不是text 传递到Replace,这样您就不会丢失第一个更改。
  • 您得到的异常是由于正则表达式无效。
  • @Jacob 谢谢!我找到了
  • 在其当前源代码形式@"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$" 中不包含解析错误。
  • @sln 在其以前的形式中以 ? 开头

标签: c# regex dictionary iteration


【解决方案1】:
public static string Replacements(string text)
{

    string output = text;
    foreach (KeyValuePair<string, string> item in dict1)
    {
        //here replace output again
        output = Regex.Replace(output, item.Key, item.Value); 

    }


    return output;
}

如果要应用许多替换,则需要替换上一个操作的结果。

【讨论】:

  • 我得到一个未处理的参数错误。我猜这是因为正则表达式什么也没找到,也没有继续?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多