四联光电智能照明论坛

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1998|回复: 0
打印 上一主题 下一主题

C# Regex类用法

[复制链接]
  • TA的每日心情
    开心
    2018-12-28 16:25
  • 817

    主题

    1556

    帖子

    1万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    14941
    跳转到指定楼层
    楼主
    发表于 2016-11-7 09:43:59 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

    使用Regex类需要引用命名空间:using System.Text.RegularExpressions;
    利用Regex类实现验证
    示例1:注释的代码所起的作用是相同的,不过一个是静态方法,一个是实例方法
    1. var source = "刘备关羽张飞孙权";
    2. //Regex regex = new Regex("孙权");
    3. //if (regex.IsMatch(source))
    4. //{
    5. // Console.WriteLine("字符串中包含有敏感词:孙权!");
    6. //}
    7. if (Regex.IsMatch(source, "孙权"))
    8. {
    9.   Console.WriteLine("字符串中包含有敏感词:孙权!");
    10. }
    11. Console.ReadLine();
    复制代码


    示例2:使用带两个参数的构造函数,第二个参数指示忽略大小写,很常用
    1. var source = "123abc345DEf";
    2. Regex regex = new Regex("def",RegexOptions.IgnoreCase);
    3. if (regex.IsMatch(source))
    4. {
    5.   Console.WriteLine("字符串中包含有敏感词:def!");
    6. }
    7. Console.ReadLine();
    复制代码


    使用Regex类进行替换

    示例1:简单情况
    1. var source = "123abc456ABC789";
    2. // 静态方法
    3. //var newSource=Regex.Replace(source,"abc","|",RegexOptions.IgnoreCase);
    4. // 实例方法
    5. Regex regex = new Regex("abc", RegexOptions.IgnoreCase);
    6. var newSource = regex.Replace(source, "|");
    7. Console.WriteLine("原字符串:"+source);
    8. Console.WriteLine("替换后的字符串:" + newSource);
    9. Console.ReadLine();
    复制代码


    结果:
    原字符串:123abc456ABC789
    替换后的字符串:123|456|789

    示例2:将匹配到的选项替换为html代码,我们使用了MatchEvaluator委托
    1. var source = "123abc456ABCD789";
    2. Regex regex = new Regex("[A-Z]{3}", RegexOptions.IgnoreCase);
    3. var newSource = regex.Replace(source,new MatchEvaluator(OutPutMatch));
    4. Console.WriteLine("原字符串:"+source);
    5. Console.WriteLine("替换后的字符串:" + newSource);
    6. Console.ReadLine();

    7. private static string OutPutMatch(Match match)
    8. {
    9.   return "<b>" +match.Value+ "</b>";
    10. }
    复制代码


    输出:
    原字符串:123abc456ABCD789
    替换后的字符串:123<b>abc</b>456<b>ABC</b>D789
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|Archiver|手机版|小黑屋|Silian Lighting+ ( 蜀ICP备14004521号-1 )

    GMT+8, 2024-5-6 21:07 , Processed in 1.078125 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2013 Comsenz Inc.

    快速回复 返回顶部 返回列表