C#中的正则表达式介绍

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

该示例产生下面的输出:

Number of groups found = 3

3.5 CaptureCollection 类表示捕获的子字符串的序列

由于限定符,捕获组可以在单个匹配中捕获多个字符串。Captures属性(CaptureCollection 类的对象)是作为 Match 和 group 类的成员提供的,以便于对捕获的子字符串的集合的访问。例如,如果使用正则表达式 ((a(b))c)+(其中 + 限定符指定一个或多个匹配)从字符串"abcabcabc"中捕获匹配,则子字符串的每一匹配的 Group 的 CaptureCollection 将包含三个成员。

下面的程序使用正则表达式 (Abc)+来查找字符串"XYZAbcAbcAbcXYZAbcAb"中的一个或多个匹配,阐释了使用 Captures 属性来返回多组捕获的子字符串。

 

 
  1. using System;   using System.Text.RegularExpressions;  
  2. public class RegexTest   {  
  3. public static void RunTest()   {  
  4. int counter;   Match m;  
  5. CaptureCollection cc;   GroupCollection gc;  
  6. Regex r = new Regex("(Abc)+"); //查找"Abc"   m = r.Match("XYZAbcAbcAbcXYZAbcAb"); //设定要查找的字符串  
  7. gc = m.Groups;   //输出查找组的数目  
  8. Console.WriteLine("Captured groups = " + gc.Count.ToString());   // Loop through each group.  
  9. for (int i=0; i < gc.Count; i++) //查找每一个组   {  
  10. cc = gc.Captures;   counter = cc.Count;  
  11. Console.WriteLine("Captures count = " + counter.ToString());   for (int ii = 0; ii < counter; ii++)  
  12. {   // Print capture and position.  
  13. Console.WriteLine(cc[ii] + " Starts at character " +   cc[ii].Index); //输入捕获位置  
  14. }   }  
  15. }   public static void Main() {  
  16. RunTest();   }  
  17. }