Csharp/C#教程:迭代C#中的Regex字典分享


迭代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; } 

如果要应用多个替换,则需要替换先前操作的结果。

上述就是C#学习教程:迭代C#中的Regex字典分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1016757.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐