C#正则表达式MatchCollection类表示非重叠匹配的序列
该集合为只读的,并且没有公共构造函数。MatchCollection 的实例是由 Regex.Matches 属性返回的。使用 Regex 类的 Matches 方法,通过在输入字符串中找到的所有匹配填充 MatchCollection。下面代码示例演示了如何将集合复制到一个字符串数组(保留每一匹配)和一个整数数组(指示每一匹配的位置)中。
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; //记录匹配字符的位置
}
可以将 蓝色背景中的内容
换为 黄色背景部分
foreach(match mc1 in mc)
{
results[i]=mc1.value;
matchposition[i]=mc1.index;
}
其结果为:results[0]=abc;results[1]=abc;
matchposition[0]=3; matchposition[0]=7;