zoukankan      html  css  js  c++  java
  • C#探秘系列(六)

    正则表达式与Regex类

    一、正则表达式

    正则表达式是一种用来描述和操作文本的强大语言。正则表达式主要用于字符串,即一组字符。当然,正则表达式的内容可以用一整本书来详细阐述,所以在这里仅介绍在C#中常用的规则。

    1.正则表达式元字符

    正则表达式语言由两种基本字符类型组成:原义(正常)文本字符和元字符。元字符使正则表达式具有处理能力。元字符既可以是放在 [] 中的任意单个字符(如 [a] 表示匹配单个小写字符 a ),也可以是字符序列(如 [a-d] 表示匹配 a、b 、c、 d 之间的任意一个字符,而 w 表示任意英文字母和数字及下划线),下面是一些常见的元字符:

    元字符 详细说明
    . 匹配除 以外的任何字符
    [abcde] 匹配abcde之中的任意一个字符
    [a-h] 匹配a到h之间的任意一个字符
    [^fgh] 不与fgh之中的任意一个字符匹配
    w 匹配大小写英文字符及数字0-9之间的任意一个及下划线,相当于[a-zA-Z0-9]
    W 不匹配大小写英文字符及数字0-9之间的任意一个, 相当于[^a-zA-Z0-9]
    s 匹配任何空白字符,相当于[f v]
    S 匹配任何非空白字符,相当于[^s]
    d 匹配任何0-9之间的单个数字, 相当于[0-9]
    D 不匹配任何0-9之间的单个数字,相当于[^0-9]
    [u4e00-u9fa5] 匹配任意单个汉字(这里用的是Unicode编码表示汉字的)

    2.正则表达式限定符

    上面的元字符都是针对单个字符匹配的,要想同时匹配多个字符的话,还需要借助限定符。下面是一些常见的限定符(下表中n和m都是表示整数,且0 < n < m ):

    限定符 详细说明
    * 匹配0到多个元字符,相当于{0,}
    匹配0-1个元字符,相当于{0,1}
    {n} 匹配n个字符
    {n,} 匹配至少n个元字符
    {n, m} 匹配n-m个元字符
    + 匹配至少1个元字符,相当于{1,}
     匹配单词边界
    ^ 字符串必须以指定的字符开始
    $ 字符中必须以指定的字符结束

    参考 http://www.cnblogs.com/JensonBin/archive/2011/09/13/2174611.html

    二、Regex类

    C#中提供的Regex类可以实现正则表达式的匹配、替换与分割等功能,它代表了不可变的可编译的正则表达式。其定义在源文件System.Text.RegularExpressions中。

    1.匹配功能

    首先定义两个变量:

    String source = "04:03:27 127.0.0.0 LibertyAssociates.com " +
                    "04:03:28 127.0.0.0 foo.com " + "04:03:29 127.0.0.0 bar.com ";
    Regex regex = new Regex(@"d");                

    Regex(@”d”)用指定的正则表达式初始化Regex类,用于匹配单数字。

    1)判断是否匹配

    if (regex.IsMatch(source))
                    Console.WriteLine("The String has number!");
    //output: The String has number!                

    2)获取匹配数目

    int count = regex.Matches(source).Count;
                    Console.WriteLine("The String has {0} numbers!", count);
    //output:The String has 36 numbers!                

    3)获取匹配值

    //the first method: using Match method
    String match = regex.Match(source).Value;
                    Console.WriteLine("The String has the number {0}!", match); 
    //output:The String has the number 1!                
    //the second method: using MatchGroup mehtod 
    String matchGroup = regex.Match("ag123ssf23df").Groups[0].Value;
                    Console.WriteLine("The String has a group of number {0}!", matchGroup);               
    //output:The String has a group of number 1!                

    4)利用Groups匹配分组

    Regex theReg = new Regex(@"(?<time>(d|:)+)s" 
                                            +@"(?<ip>(d|.)+)s" + @"(?<site>S+)");
                // get the collection of matches
                MatchCollection theMatches = theReg.Matches(source);
                    foreach (Match theMatch in theMatches)
                {// iterate through the collection
                     if (theMatch.Length != 0)
                    {
                        Console.WriteLine("
    theMatch: {0}", theMatch.ToString());
                        Console.WriteLine("time: {0}", theMatch.Groups["time"].Value);
                        Console.WriteLine("ip: {0}", theMatch.Groups["ip"].Value);
                        Console.WriteLine("site: {0}", theMatch.Groups["site"].Value);
                    }
                }
    //output:
    
    theMatch: 04:03:27 127.0.0.0 LibertyAssociates.com
    time: 04:03:27
    ip: 127.0.0.0
    site: LibertyAssociates.com
    
    theMatch: 04:03:28 127.0.0.0 foo.com
    time: 04:03:28
    ip: 127.0.0.0
    site: foo.com
    
    theMatch: 04:03:29 127.0.0.0 bar.com
    time: 04:03:29
    ip: 127.0.0.0
    site: bar.com
    请按任意键继续. . .            

    2.替换功能

    1)Replace()替换

    Regex replaceRex = new Regex(" ");
                    String result = replaceRex.Replace(source, " | ");
                    Console.WriteLine("
    The result is: {0} ", result);
    //output:
    The result is: 04:03:27 | 127.0.0.0 | LibertyAssociates.com | 04:03:28 | 127.0.0
    .0 | foo.com | 04:03:29 | 127.0.0.0 | bar.com
    请按任意键继续. . .

    2)使用 MatchEvaluator 委托替换

    using System;
    using System.Text.RegularExpressions;
    
    class MyClass
    {
       static void Main(string[] args)
       {
          string sInput, sRegex;
    
          // The string to search.
          sInput = "aabbccddeeffcccgghhcccciijjcccckkcc";
    
          // A very simple regular expression.
          sRegex = "cc";
    
          Regex r = new Regex(sRegex);
    
          MyClass c = new MyClass();
    
          // Assign the replace method to the MatchEvaluator delegate.
          MatchEvaluator myEvaluator = new MatchEvaluator(c.ReplaceCC);
    
          // Write out the original string.
          Console.WriteLine(sInput);
    
          // Replace matched characters using the delegate method.
          sInput = r.Replace(sInput, myEvaluator);
    
          // Write out the modified string.
          Console.WriteLine(sInput);
       }
    
       public string ReplaceCC(Match m)
       // Replace each Regex cc match with the number of the occurrence.
       {
          i++;
          return i.ToString() + i.ToString();       
       }
       public static int i=0;
    }
    // The example displays the following output:
    //       aabbccddeeffcccgghhcccciijjcccckkcc
    //       aabb11ddeeff22cgghh3344iijj5566kk77
  • 相关阅读:
    包的使用,json&pickle模块,hashlib模块
    在阿里云购买云服务器并安装宝塔面板
    python 采集斗图啦(多线程)
    python 采集斗图啦xpath
    python 采集唯美girl
    小程序接入内容内容审查接口(图片.文字)
    PEP8规范
    接口的安全问题
    学习redis知识的过程
    Spring葵花宝典
  • 原文地址:https://www.cnblogs.com/jscitlearningshare/p/4439738.html
Copyright © 2011-2022 走看看