您的位置:首页 > 编程语言 > C#

通过代码学习C#&.NET——委托使用(正则表达式替换)

2011-10-23 01:14 766 查看
代码编写及运行环境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");
}
}
}


运行结果为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: