用于正则表达式的 Regex.Matches静态方法的几种用法:
-
- string Text = @"This is a book , this is my book , Is not IIS";
-
-
- string Pattern = "is";
-
- MatchCollection Matches = Regex.Matches(
- Text,
- Pattern,
- RegexOptions.IgnoreCase |
- RegexOptions.ExplicitCapture |
- RegexOptions.RightToLeft
- );
-
- Console.WriteLine("从右向左匹配字符串:");
-
- foreach (Match NextMatch in Matches)
- {
- Console.Write("匹配的位置:{0,2} ", NextMatch.Index);
- Console.Write("匹配的内容:{0,2} ", NextMatch.Value);
- Console.Write("/n");
- }
-
- Console.WriteLine();
-
-
-
- Pattern = @"/bI";
- Matches = Regex.Matches(
- Text,
- Pattern,
- RegexOptions.ExplicitCapture
- );
-
- Console.WriteLine("从左向右匹配字符串:");
-
- foreach (Match NextMatch in Matches)
- {
- Console.Write("匹配的位置:{0} ", NextMatch.Index);
- Console.Write("匹配的内容:{0} ", NextMatch.Value);
- Console.Write("/n");
- }
-
- Console.WriteLine();
-
-
-
-
- Pattern = @"/bI/S*S/b";
- Matches = Regex.Matches(
- Text,
- Pattern,
- RegexOptions.ExplicitCapture
- );
-
- Console.WriteLine("从左向右匹配字符串:");
-
- foreach (Match NextMatch in Matches)
- {
- Console.Write("匹配的位置:{0} ", NextMatch.Index);
- Console.Write("匹配的内容:{0} ", NextMatch.Value);
- Console.Write("/n");
- }
-
- Console.WriteLine();
-
-
- Pattern = @"[h|i]is";
- Matches = Regex.Matches(
- Text,
- Pattern,
- RegexOptions.IgnoreCase |
- RegexOptions.ExplicitCapture
- );
-
- Console.WriteLine("从左向右匹配字符串:");
-
- foreach (Match NextMatch in Matches)
- {
- Console.Write("匹配的位置:{0} ", NextMatch.Index);
- Console.Write("匹配的内容:{0} ", NextMatch.Value);
- Console.Write("/n");
- }
-
- Console.WriteLine();
-
-
- Text = "http://192.168.0.1:2008";
- Pattern = @"/b(/S+)://(/S+)(?::(/S+))/b";
- Matches = Regex.Matches(Text, Pattern);
-
- Console.WriteLine("从左向右匹配字符串:");
-
- foreach (Match NextMatch in Matches)
- {
- Console.Write("匹配的位置:{0} ", NextMatch.Index);
- Console.Write("匹配的内容:{0} ", NextMatch.Value);
- Console.Write("/n");
-
- for (int i = 0; i < NextMatch.Groups.Count; i++)
- {
- Console.Write("匹配的组 {0}:{1,4} ", i + 1, NextMatch.Groups[i].Value);
- Console.Write("/n");
- }
- }
-
- Console.Read();
输出结果为:
- ①从右向左匹配字符串:
- 匹配的位置:43 匹配的内容:IS
- 匹配的位置:35 匹配的内容:Is
- 匹配的位置:22 匹配的内容:is
- 匹配的位置:19 匹配的内容:is
- 匹配的位置: 5 匹配的内容:is
- 匹配的位置: 2 匹配的内容:is
-
- ②从左向右匹配字符串:
- 匹配的位置:35 匹配的内容:I
- 匹配的位置:42 匹配的内容:I
-
- ③从左向右匹配字符串:
- 匹配的位置:42 匹配的内容:IIS
-
- ④从左向右匹配字符串:
- 匹配的位置:1 匹配的内容:his
- 匹配的位置:18 匹配的内容:his
- 匹配的位置:42 匹配的内容:IIS
-
- ⑤从左向右匹配字符串:
- 匹配的位置:0 匹配的内容:http:
- 匹配的组 1:http:
- 匹配的组 2:http
- 匹配的组 3:192.168.0.1
- 匹配的组 4:2008