正则表达式 - 文本规则替换器
源自一篇帖子:http://topic.csdn.net/u/20100719/21/25879eed-7555-4ce6-b6ec-e00271838b5a.html?seed=505778035&r=67090922#r_67090922其实类似的东西以前写过,再次出现,就又写了一次,避免再写下一次重造车轮子,贴在博客上好了。//Createdbywuyazhe@2010-7-20//引用时请保留作者声明usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Text.RegularExpressions;namespaceCSharpConsole02{classProgram{staticvoidMain(string[]args){//构造规则字典Dictionaryrule=newDictionary();rule.Add("LS","连接成功");rule.Add("DA","日期");rule.Add("TI","时间");rule.Add("GI","入住");rule.Add("RN","房间号");rule.Add("G#","客人编号");rule.Add("GN","姓名");rule.Add("GL","语言");rule.Add("GV","VIP会员");rule.Add("GO","退房");rule.Add("GS","共享");rule.Add("GSN","不共享");//构造测试数组string[]lines=newstring[]{"LS|DA100719|TI161039|","GI|RN3017|G#17277|GN(EN)MrMessi|GLEA|GV1|","GO|RN1007|G#17277|GSN|"};//依次替换显示foreach(stringlineinlines){Console.WriteLine(MultiReplace(line,rule));}Console.ReadKey();}//////规则替换方法//////要替换的文本///规则字典///替换后的文本publicstaticstringMultiReplace(strings,Dictionaryrule){//创建规则文本StringBuilderregexBuilder=newStringBuilder();foreach(stringkeyinrule.Keys)regexBuilder.Append(Regex.Escape(key)+"|");regexBuilder.Remove(regexBuilder.Length-1,1);returnRegex.Replace(s,regexBuilder.ToString(),delegate(Matchm){returnrule[m.Value];});}}}