分享一个自己项目中用到的.net中正则替换工具处理类(支持先用特征匹配内容整体模板,同时模板内对相关字内容进行替换)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace ConfigLab.Comp.DataType { /// <summary> /// 功能简介:正则替换的封装处理 /// 创建时间:2020-6-26 /// 创建人:pcw
/// 博客:https://www.cnblogs.com/taohuadaozhu /// 用法: ///RegReplaceWrapper rrp = new RegReplaceWrapper(); ///rrp.setReplacementForMatchContext("abc", "123"); ///MessageBox.Show(rrp.getReplaceResult("混淆代码前开始测试匹配abc,[abc],tabce, abc cab ", @"\[([a-zA-Z]+)\]")); ///MessageBox.Show(rrp.getReplaceResult("混淆代码前开始测试匹配abc,[abc],tabce, abc cab abc(); ", @"[^a-zA-Z0-9\u4e00-\u9fa5](abc)[^a-zA-Z0-9\u4e00-\u9fa5]")); /// </summary> public class RegReplaceWrapper { private string targetitem = ""; private string replacement = ""; /// <summary> /// 设置纯粹的替换(不考虑模式和所属上下文) /// </summary> /// <param name="sTargetItem"></param> /// <param name="sReplacement"></param> public void setReplacementForMatchContext(string sTargetItem, string sReplacement) { this.targetitem = sTargetItem; this.replacement = sReplacement; } private string setFormatOnMatch(Match match) { if (string.IsNullOrEmpty(this.targetitem) == false) { return match.Value.Replace(this.targetitem, this.replacement); } return match.Value; } public string getReplaceResult(string sSourceText, string sPattern, RegexOptions eRegexOptions = RegexOptions.Multiline) { try { return Regex.Replace(sSourceText, sPattern, new MatchEvaluator(setFormatOnMatch), eRegexOptions); } catch (Exception ex) { } return sSourceText; } } }