zoukankan      html  css  js  c++  java
  • Regex入门(一)

    Regex入门(一)

    平时正则表达式接触的比较多,但是大多数都是走马观花形式的,要了去搜索,看了就忘。今天温习了下,把成果写出来,做个总结:

    下面介绍的都是简单的用法,复杂点的明天继续,呵呵:

    Regex. IsMatch用法

     //简单匹配某单词

                Console.WriteLine("\n\nIsMatch演示:");
                Regex reg 
    = new Regex("aaron");
                Console.WriteLine(
    string.Format("result1: {0}", reg.IsMatch("my name is aaron.")));     //True
                Console.WriteLine(string.Format("result2: {0}", reg.IsMatch("my name is arron.")));     //False

     //默认是区分大小写的,所以下面2个会返回不同的结果

                Console.WriteLine(string.Format("result3: {0}", Regex.IsMatch("my name is aaron.""Aaron")));      //False
                Console.WriteLine(string.Format("result4: {0}", Regex.IsMatch("my name is arron.""aaron")));      //False

     //这个是不区分大小写的

                Console.WriteLine(string.Format("result3: {0}", Regex.IsMatch("my name is aaron.""Aaron", RegexOptions.IgnoreCase)));     //True

    Regex. Replace用法

    简单替换某单词

    //简单替换某单词
                Console.WriteLine("\n\nReplace演示:");
                reg
    =new Regex("r");
                Console.WriteLine(
    string.Format("result4: {0}", reg.Replace("my name is arron.""R")));                            //my name is aRRon.
                Console.WriteLine(string.Format("result4: {0}", reg.Replace("my name is arron.""R"1)));//只进行一次替换         //my name is aRron.

    Regex.Match用法

     //**********************Match用法*****************************

                Console.WriteLine("\n\nMatch演示:");
                reg 
    = new Regex("aa...");//开头2个字母必须是aa,并且后面跟任意3个字符
                Match m=reg.Match("my name is aaron, aaRON, Aaron");
                
    while(m.Success)
                {
                    Console.WriteLine(m.Value);
                    m 
    = m.NextMatch();
                    
    //这里由于默认是区分大小写的,所以
                    
    //  aaron       是Match的
                    
    //  aaRON       也是Match的
                    
    //  Aaron       不会Match
                }

    Regex.Matchs用法

    //******************MatchsCollection用法***********************
                Console.WriteLine("\n\nMatchsCollection演示:");
                MatchCollection mc 
    = Regex.Matches("my name is aaron, aaRON, Aaron""aa...");//开头2个字母必须是aa,并且后面跟任意3个字符

                Console.WriteLine(string.Format("found: {0}", mc.Count)); 

  • 相关阅读:
    [C#.net]获取文本文件的编码,自动区分GB2312和UTF8
    [C#.net]SqlDataAdapter 执行超时已过期 完成操作之前已超时或服务器未响应
    [C#.Net]Window服务调用外部程序
    [Bat]UNC路径不支持的2种解决方法
    [c#.net]未能加载文件或程序集“”或它的某一个依赖项。系统找不到指定的文件
    精读比特币论文
    动态添加Redis密码认证
    扫码登录的安全性分析
    Cookie与Passport安全
    Http压测工具wrk使用指南
  • 原文地址:https://www.cnblogs.com/aarond/p/2041554.html
Copyright © 2011-2022 走看看