標籤:
C#中有關Regex的類包含在System.Text.RegularExpressions命名空間中,可通過一下代碼添加該命名空間:
1 using System.Text.RegularExpressions;
View Code
字串匹配中,主角是"被匹配串"和"匹配模式"。
1 // 定義 "被匹配串" 2 string message = " mother father sister brother "; 3 // 定義 "匹配模式" 4 string pattern = @"\b(\w+)ther\b"; 5 // 用靜態方法進行匹配,也可以通過建立正則對象進行匹配 6 MatchCollection matches = Regex.Matches(message, pattern); 7 // 遍曆得到的結果 8 foreach (Match match in matches) { 9 Console.WriteLine("Groups[0].Value = {0} --- Groups[1].Value = {1}", match.Groups[0].Value, matchGroups[1].Value); 10 } 11 12 // 輸出13 // Groups[0].Value = mother --- Groups[1].Value = mo14 // Groups[0].Value = father --- Groups[1].Value = fa15 // Groups[0].Value = brother --- Groups[1].Value = bro16 // 結束輸出
這是其中一個樣本,匹配方法有三種: IsMatch(), Match(), Matches().
如果只是想知道"被匹配串"中是否包含某種"匹配模式", 可以使用IsMatch();
如果想得到一個匹配到的結果,可以使用Match();
如果想得到多個匹配到的結果,可以使用Matches();
單個匹配到的結果可以使用Groups[]擷取利用"匹配模式"匹配的分組,以便對匹配得到的資訊的利用。
具體使用規則:http://www.dotnetperls.com/regex-match
C#中Regex的簡單使用