C#中正则表达式只取前N个匹配结果

用Regex.Matches方法可以得到同指定正则表达式对应的所有匹配结果。有时,所有匹配结果可能有成千上万个,考虑到性能效率的因素,只需要取出前N个匹配结果。下面的代码演示了做法:

需求:取字符串中前3个数值(相连的数字)。

[csharp] view plaincopy
  1. Match match = Regex.Match("12ab34de567ab890", @"d+");  
  2. for (int i = 0; i < 3; i++)  
  3. {  
  4.     if (match.Success)  
  5.     {  
  6.         Response.Write(match.Value + "<br/>");  
  7.         match = match.NextMatch();  
  8.     }  
  9. }  

输出:

12

34

567

原文地址:https://www.cnblogs.com/gc2013/p/3984991.html