二、使用Regex类进行替换
示例1:简单情况
var srcStr2 = "123abc[IT.Hxw.Red]345456cn"; // 静态方法 //var newsrcStr=Regex.Replace(srcStr,"it","www",RegexOptions.IgnoreCase); // 实例方法 Regex regex2 = new Regex("it", RegexOptions.IgnoreCase); string newsrcStr = regex2.Replace(srcStr2, "www"); Console.WriteLine("原字符串:" + srcStr2); Console.WriteLine("替换后的字符串:" + newsrcStr);
结果:
原字符串:123abc[IT.Hxw.Red]345456cn
替换后的字符串:123abc[www.Hxw.Red]345456cn
示例2:将匹配到的选项替换为html代码,我们使用了MatchEvaluator委托
string srcStr3 = "123abc[IT.Hxw.Red]345456cn"; Regex regex3 = new Regex("[A-Z]{3}", RegexOptions.IgnoreCase); string newsrcStr1 = regex3.Replace(srcStr3,new MatchEvaluator(OutPutMatch)); Console.WriteLine("原字符串:"+srcStr3); Console.WriteLine("替换后的字符串:" + newsrcStr1); private static string OutPutMatch(Match match) { return "<b>" +match.Value+ "</b>"; }
输出:
原字符串:123abc[IT.Hxw.Red]345456cn
替换后的字符串:123<b>abc</b>[IT.<b>Hxw</b>.<b>Red</b>]345456cn