正则表达式高级替换

正则表达式的高级替换也就是可以自定函数,获取到匹配的内容然后进行进一步处理

C#方式:

主要使用到了 MatchEvaluator 对象,传入一个自定义函数即可

ReplaceFunciton中 m.Value 获取当前匹配到的内容

1 string Pattern = @"w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*";
2         Regex re = new Regex(Pattern);
3         return re.Replace(rawTxt, new MatchEvaluator(ReplaceFunction));
4 
5 private static string ReplaceFunction(Match m)
6 {
7         return String.Format("{{#{0}#}}", m.Value);
8 }

JS方式:

  replace 函数第一个参数是正则表达式,注意必须在表达式后面添加 gfunciton 就是自定义的函数,match 可以用来获取当前匹配的内容

1     var newHtml = $(selector).html().replace(/{#S*?#}/g, function (match) {
2         return hex2str(match.substring(2, match.length - 2));
3     });
原文地址:https://www.cnblogs.com/TianyuSu/p/10382132.html