.NET 正则表达式 类型 Match Group Capture

这几个概念比较细致,见如下程序演示。
1 using System;
2  using System.Collections.Generic;
3  using System.Linq;
4  using System.Text;
5  using System.Text.RegularExpressions;
6
7  namespace RegExFindArgs
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 Experiment();
14 }
15
16 public static void Experiment()
17 {
18 Regex regex = new Regex(@"(([A-Z])+(\d)+)", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled);
19 String test = "ABC12345";
20 MatchCollection mc = regex.Matches(test);
21 Console.WriteLine("MatchCollection count:{0}", mc.Count);
22 Console.WriteLine("----------------");
23
24 for (Int32 mc_i = 0; mc_i < mc.Count; mc_i++)
25 {
26 Console.WriteLine("Match[{0}].Value:[{1}]", mc_i, mc[mc_i].Value);
27 GroupCollection gc = mc[mc_i].Groups;
28 Console.WriteLine(" There're {0} groups in this match", gc.Count);
29
30 for (Int32 gc_i = 0; gc_i < gc.Count; gc_i++)
31 {
32 Console.WriteLine(" Group[{0}].Value:[{1}]", gc_i, gc[gc_i].Value);
33
34 CaptureCollection cc = gc[gc_i].Captures;
35 Console.WriteLine(" There're {0} captures in this group", cc.Count);
36 for (Int32 cc_i = 0; cc_i < cc.Count; cc_i++)
37 {
38 Console.WriteLine(" Capture[{0}].Value:[{1}]", cc_i, cc[cc_i].Value);
39 }
40 }
41 }
42 }
43 }
44 }
45  

输出:

1 MatchCollection count:1
2 ----------------
3 Match[0].Value:[ABC12345]
4 There're 4 groups in this match
5 Group[0].Value:[ABC12345]
6 There're 1 captures in this group
7 Capture[0].Value:[ABC12345]
8 Group[1].Value:[ABC12345]
9 There're 1 captures in this group
10 Capture[0].Value:[ABC12345]
11 Group[2].Value:[C]
12 There're 3 captures in this group
13 Capture[0].Value:[A]
14 Capture[1].Value:[B]
15 Capture[2].Value:[C]
16 Group[3].Value:[5]
17 There're 5 captures in this group
18 Capture[0].Value:[1]
19 Capture[1].Value:[2]
20 Capture[2].Value:[3]
21 Capture[3].Value:[4]
22 Capture[4].Value:[5]

相关参考:http://www.cn-cuckoo.com/2007/07/26/math-group-and-capture-42.html

原文地址:https://www.cnblogs.com/smwikipedia/p/1667927.html