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

5 篇文章 0 订阅

代码编写及运行环境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");
        }
    }
}


运行结果为:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值