C#中的正则表达式介绍

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

此例返回下面的输出结果:

 

 
  1. Captured groups = 2   Captures count = 1  
  2. AbcAbcAbc Starts at character 3   Captures count = 3  
  3. Abc Starts at character 3   Abc Starts at character 6  
  4. Abc Starts at character 9  

3.6 Capture 类包含来自单个子表达式捕获的结果

在 Group 集合中循环,从 Group 的每一成员中提取 Capture 集合,并且将变量 posn 和 length 分别分配给找到每一字符串的初始字符串中的字符位置,以及每一字符串的长度。

 

 
  1. Regex r;   Match m;  
  2. CaptureCollection cc;   int posn, length;  
  3. r = new Regex("(abc)*");   m = r.Match("bcabcabc");  
  4. for (int i=0; m.Groups.Value != ""; i++)   {  
  5. cc = m.Groups.Captures;   for (int j = 0; j < cc.Count; j++)  
  6. {   posn = cc[j].Index; //捕获对象位置  
  7. length = cc[j].Length; //捕获对象长度   }  
  8. }