標籤:style blog http io os 使用 ar for 2014
1, C#中與Regex相關類。
C#中與Regex相關類的幾個常用類是Regex,Match,Group,Captrue,RegexOption首先我們看看這幾個類的類圖關係,如何你有Regex基礎,從這些方法和屬性中就大概能明白使用方法了。
Regex:與Regex相關的操作必須通過它來執行的,它還提供了Match,IsMatch,Replace,Split幾個靜態方法。
ResgexOptions:初始化Regex執行個體的時候,可以指定匹配的選項,如忽略大小寫,多行模式等。
Match:一個匹配結果,其中還包含分組Group的一個集合。其中Index為0的分組是預設分組,不管Regex中有沒有分組,這個Group都是存在的。所以在處理自訂的分組時,要跳過這個分組。
Group:一個分組,包含多個Capture。
Capture:一個捕獲。
這3個類有繼承關係,可以看上面的例子,所以一些屬性如Value在3個類中都是存在的。
2, 簡單使用
// 檢查是否是數字 if (Regex.IsMatch("956", "[0-9]+")) { System.Diagnostics.Debug.WriteLine("數字匹配成功");// 結果:數字匹配成功 } // 檢查是否是字母(忽略大小寫) if (Regex.IsMatch("abcABC", "[a-z]+", RegexOptions.IgnoreCase)) { System.Diagnostics.Debug.WriteLine("字元匹配成功");// 結果:字元匹配成功 } // 替換‘abc’(忽略大小寫)為‘@’ string res = Regex.Replace("i abc like ABC it", "abc", "@", RegexOptions.IgnoreCase); // 結果:i @ like @ it // 以‘abc’(忽略大小寫)拆分字串 string[] splits = Regex.Split("i abc like ABC it", "abc", RegexOptions.IgnoreCase); // 結果為3個字串,i,like,it// 根據匹配結果,列印出Match,Group,Capture的值 Regex regex = new Regex(this.txtPattern.Text); var matches = regex.Matches(this.txtInput.Text); string result = string.Empty; int count = matches.Count; result += "matches.Count:" + count + Environment.NewLine; foreach (Match m in matches) { result += "matche value:" + m.Value + Environment.NewLine; result += "matche group count:" + m.Groups.Count + Environment.NewLine; for (int i = 0; i < m.Groups.Count; i++) { Group g = m.Groups[i]; result += "--group " + (i + 1) + Environment.NewLine; result += "--group Value " + g.Value + Environment.NewLine; result += "--capture count:" + m.Captures.Count + Environment.NewLine; for (int j = 0; j < g.Captures.Count; j++) { Capture c = g.Captures[j]; result += "----capture " + (j + 1) + Environment.NewLine; result += "----capture Value " + c.Value + Environment.NewLine; } } }
基本的操作就這些了,一般應用中根據需要對捕獲的結果進行具體分析。
關於Regex的文法可以參考這幾篇文章:
Regex基礎:http://www.cnblogs.com/xiashengwang/p/3988009.html
Regex分組:http://www.cnblogs.com/xiashengwang/p/3988573.html
Regex的使用(C#)