常见c#正则表达式类学习整理

1.MatchCollection

用于输入字符串所找到的成功匹配的集合,Regex.Matches 方法返回 MatchCollection 对象

用法   
//str:要搜索匹配项的字符串   pattern:要匹配的正则表达式模式
MatchCollection matches = Regex.Matches(string str,string pattern)

 foreach (Match item in matches)
 {
         Console.WriteLine(item.Groups[0].Value);
 }

2.Match类

 表示正则表达式匹配操作的结果。Match 类的 Match.Success 匹配是否成功。Match.Index 返回第一个匹配的位置。

完整控制台输出:(在文本中提取字符串)

     public static void Main(string[] args)
        {           
            string text = "I've found this amazing URL at http://www.sohu.com ,and then find ftp://ftp.sohu.com is better.";
            string pattern = @"(S+)://(S+)";  //匹配URL的模式
            MatchCollection mc = Regex.Matches(text, pattern); //满足pattern的匹配集合
            Console.WriteLine("文本中包含的URL地址有:");
            foreach (Match match in mc)
            {
                Console.WriteLine(match.ToString());
            }
            Console.Read();
        }

3.Regex类

表示不可变(只读)的正则表达式,包含各种静态方法

Regex regex = new Regex(@"d"); //定义Regex类的实例;

regex.IsMatch("abc");   //判断一个字符串,是否匹配一个正则表达式

regex.Matches("abc123abc").Count;  //获取匹配次数

Regex.Match(string).Groups[int].Value   //捕获值

//去除<p></p>标签
 string str ="<p>此处是内容qqqq</p><p>此处是内容wwwww</p>";
            string regexstr = @"</?[p|P][^>]*>";  

            str = Regex.Replace(str, regexstr, string.Empty);
            Console.Write(str);
            Console.ReadKey();

4.Group

 表示来自单个捕获组的结果;(分组是要匹配的模式pattern用小括号括起来,分成不同的组)
public static void Main(string[] args)
    {
        string text = "I've found this amazing URL at http://www.sohu.com ,and then find ftp://ftp.sohu.com is better.";
        string pattern = @"(?<protocol>S+)://(?<address>S+)"; //匹配URL的模式,并分组
        MatchCollection mc = Regex.Matches(text, pattern); //满足pattern的匹配集合

        Console.WriteLine("文本中包含的URL地址有:");
        foreach (Match match in mc)
        {
            GroupCollection gc = match.Groups;
            string outputText = "URL:" + match.Value + ";Protocol:" + gc["protocol"].Value + ";Address:" + gc["address"].Value;
            Console.WriteLine(outputText);
        }

        Console.Read();
    }
    /**
     * 运行后输出如下:
     * 文本中包含的URL地址有:
     * URL:http://www.sohu.com;Protocol:http;Address:www.sohu.com
     * URL:ftp://ftp.sohu.com;Protocol:ftp;Address:ftp.sohu.com
    */

5.GroupCollection

表示被捕获的组的集合,并在单个匹配项中返回该捕获组的集合
在 Match.Groups 属性返回的集合中返回。
原文地址:https://www.cnblogs.com/wangzhe688/p/7646078.html