迭代C#中的Regex字典
我有一个函数,可以找到并替换输入字符串text
的正则表达式
public static string Replacements(string text) { string output = Regex.Replace(text, @"\b[a-zA-Z0-9.-_]+@[az][A-Z0-9.-]+\.[a-zA-Z0-9.-]+\b","email"); return output; }
假设我想将替换正则表达式放入字典中
static Dictionary dict1 = new Dictionary { {@"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$", "phoneno"}, {@"\b[a-zA-Z0-9.-_]+@[az][A-Z0-9.-]+\.[a-zA-Z0-9.-]+\b","email"}, };
我想迭代字典来替换文本。 我该怎么办? 我在这里尝试使用forloop的解决方案: 在C#中迭代Dictionary的最佳方法是什么?
public static string Replacements(string text) { string output = text; foreach (KeyValuePair item in dict1) { output = Regex.Replace(text, item.Key, item.Value); } return output; }
但它没有用。 有一个更好的方法吗? 我得到一个Argumentexception是未处理的错误:
parsing "^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$" - Quantifier {x,y} following nothing.
public static string Replacements(string text) { string output = text; foreach (KeyValuePair item in dict1) { //here replace output again output = Regex.Replace(output, item.Key, item.Value); } return output; }
如果要应用多个替换,则需要替换先前操作的结果。