1 static void Main(string[] args) 2 { 3 4 //FileStream fs = new FileStream(@"C:UsersAlexDesktopTask.txt", FileMode.Open, FileAccess.Read); 5 //StreamReader sr = new StreamReader(fs); 6 StreamReader sr = new StreamReader(@"C:UsersAlexDesktopTask.txt", Encoding.GetEncoding("gb2312")); 7 string content = sr.ReadToEnd(); 8 9 sr.Close(); 10 11 12 Console.WriteLine(content); 13 14 //Console.ReadKey(); 15 16 Regex rx= new Regex("abc"); 17 MatchCollection mc = rx.Matches("123abc4abcd"); 18 for (int i = 0; i < mc.Count; i++) 19 { 20 Console.WriteLine(mc[i].Value); 21 } 22 //string pattern = @"^[1]"; 23 //Regex rx = new Regex(pattern); 24 //string input = "18817889736 23487 3241247531432 432432145 15895565819 1834765 13"; 25 //MatchCollection matches = rx.Matches(input); 26 //foreach(Match match in matches) 27 //{ 28 // Console.WriteLine(match.Value); 29 //} 30 }
http://www.cnblogs.com/xiaobaidhg/archive/2006/09/27/515999.html
3.3 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; //记录匹配字符的位置
}