C#正则表达式CaptureCollection类是什么呢?C#正则表达式CaptureCollection类是如何使用的呢?下面让我们来具体的内容:
下面通过介绍 .NET 框架的正则表达式类,熟悉一下.NET框架下的正则表达式的使用方法。
C#正则表达式CaptureCollection类表示捕获的子字符串的序列
由于限定符,捕获组可以在单个匹配中捕获多个字符串。Captures属性(CaptureCollection 类的对象)是作为 Match 和 group 类的成员提供的,以便于对捕获的子字符串的集合的访问。例如,如果使用正则表达式 ((a(b))c)+(其中 + 限定符指定一个或多个匹配)从字符串"abcabcabc"中捕获匹配,则子字符串的每一匹配的 Group 的 CaptureCollection 将包含三个成员。
下面的程序使用正则表达式 (Abc)+来查找字符串"XYZAbcAbcAbcXYZAbcAb"中的一个或多个匹配,阐释了使用 Captures 属性来返回多组捕获的子字符串。
C#正则表达式CaptureCollection类实例应用:
using System;
using System.Text.RegularExpressions;
public class RegexTest
{
public static void RunTest()
{
int counter;
Match m;
CaptureCollection cc;
GroupCollection gc;
Regex r = new Regex("(Abc)+"); //查找"Abc"
m = r.Match("XYZAbcAbcAbcXYZAbcAb"); //设定要查找的字符串
gc = m.Groups;
//输出查找组的数目
Console.WriteLine("Captured groups = " + gc.Count.ToString());
// Loop through each group.
for (int i=0; i < gc.Count; i++) //查找每一个组
{
cc = gc[i].Captures;
counter = cc.Count;
Console.WriteLine("Captures count = " + counter.ToString());
for (int ii = 0; ii < counter; ii++)
{
// Print capture and position.
Console.WriteLine(cc[ii] + " Starts at character " +
cc[ii].Index); //输入捕获位置
}
}
}
public static void Main() {
RunTest();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
此例返回下面的输出结果:
Captured groups = 2
Captures count = 1
AbcAbcAbc Starts at character 3
Captures count = 3
Abc Starts at character 3
Abc Starts at character 6
Abc Starts at character 9
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
C#正则表达式CaptureCollection类的基本内容就向你介绍到这里,希望对你了解和学习C#正则表达式CaptureCollection类有所帮助。
【编辑推荐】