C#中的正则表达式介绍

2019-12-30 10:56:17王旭

 

 
  1. MatchCollection mc;   String[] results = new String[20];  
  2. int[] matchposition = new int[20];   Regex r = new Regex("abc"); //定义一个Regex对象实例  
  3. mc = r.Matches("123abc4abcd");   for (int i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配  
  4. {   results = mc.Value; //将匹配的字符串添在字符串数组中  
  5. matchposition = mc.Index; //记录匹配字符的位置   }  

3.4 GroupCollection 类表示捕获的组的集合

该集合为只读的,并且没有公共构造函数。GroupCollection 的实例在 Match.Groups 属性返回的集合中返回。下面的控制台应用程序查找并输出由正则表达式捕获的组的数目。

 

 
  1. using System;   using System.Text.RegularExpressions;  
  2. public class RegexTest   {  
  3. public static void RunTest()   {  
  4. Regex r = new Regex("(a(b))c"); //定义组   Match m = r.Match("abdabc");  
  5. Console.WriteLine("Number of groups found = " + m.Groups.Count);   }  
  6. public static void Main()   {  
  7. RunTest();   }  
  8. }