代码编写及运行环境Visual Studio 2010 .NET v4.0.30319
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace DelegateUseInRegexReplace
{
/// <summary>
/// 有的时候通过正则表达式替换字符串中匹配内容中部分内容,需要使用委托实现之。
/// 本例实现的是在html源代码转换可能出现的一种情况,即需要对超链接中href属性中的域名或IP进行整体的替换
/// 本例中是把IP地址192.168.1.23替换为202.145.65.15
/// 正则表达式替换中的委托MatchEvaluator匹配的是具有一个Match参数返回string的方法
/// </summary>
class Program
{
static void Main(string[] args)
{
string html = "<br /><a href=\"http://192.168.1.23/index.html\">192.168.1.23/index.html</a>";
Console.WriteLine("原始字符串:");
Console.WriteLine(html);
string htmlResult = Regex.Replace(html, "<a[^<]*>", new MatchEvaluator(ReplaceIP));
Console.WriteLine("替换后字符串:");
Console.WriteLine(htmlResult);
}
public static string ReplaceIP(Match match)
{
return match.Value.Replace("192.168.1.23", "202.145.65.15");
}
}
}
运行结果为:
![](http://hi.csdn.net/attachment/201110/22/0_13193037877013.gif)