MatchCollection简析

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;
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值