MatchCollection mc;
String[] results = new String[20];
int[] matchposition = new int[20];
Regex r = new Regex("abc"); //定义一个Regex对象实例
mc = r.Matches("123abc4abcd");
for (int i = 0; i < mc.Count; i ) //在输入字符串中找到所有匹配
{
results[i] = mc[i].Value; //将匹配的字符串添在字符串数组中
matchposition[i] = mc[i].Index; //记录匹配字符的位置
}
3.4 GroupCollection 类表示捕捉的组的集合
该集合为只读的,并且没有公共构造函数。GroupCollection 的实例在 Match.Groups 属性返回的集合中返回。下面的控制台应用程序查找并输出由正则表达式捕捉的组的数目。
using System;
using System.Text.RegularExpressions;
public class RegexTest
{
public static void RunTest()
{
Regex r = new Regex("(a(b))c"); //定义组
Match m = r.Match("abdabc");
Console.WriteLine("Number of groups found = " m.Groups.Count);
}
public static void Main()
{
RunTest();
}
}
该示例产生下面的输出:
Number of groups found = 3
3.5 CaptureCollection 类表示捕捉的子字符串的序列
由于限定符,捕捉组可以在单个匹配中捕捉多个字符串。Captures属性(CaptureCollection 类的对象)是作为 Match 和 group 类的成员提供的,以便于对捕捉的子字符串的集合的访问。例如,假如使用正则表达式 ((a(b))c) (其中 限定符指定一个或多个匹配)从字符串"abcabcabc"中捕捉匹配,则子字符串的每一匹配的 Group 的 CaptureCollection 将包含三个成员。
下面的程序使用正则表达式 (Abc) 来查找字符串"XYZAbcAbcAbcXYZAbcAb"中的一个或多个匹配,阐释了使用 Captures 属性来返回多组捕捉的子字符串。
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); //输入捕捉位置
评论加载中…
![]() |