【发布时间】: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