用於正則表達式的 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(); //②匹配以大寫I開頭 //“/b”是轉義序列,代表開頭和結尾(一個字的邊界,忽略空白或標點) 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(); //③匹配以大寫I開頭,大寫S結尾的字符串 //“/b”是轉義序列,代表開頭和結尾(一個字的邊界,忽略空白或標點) ///S*匹配任何不是空白的字符 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(); //④匹配his 或者iis,其中忽略大小寫 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(); //⑤對Url的分組匹配 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://192.168.0.1:2008 匹配的組 1:http://192.168.0.1:2008 匹配的組 2:http 匹配的組 3:192.168.0.1 匹配的組 4:2008
---上善若水,隨遇而安。
老子