本文實例講述了C#正則表達式匹配與替換字符串功能。分享給大家供大家參考,具體如下:
事例一:/w+=>[A-Za-z1-9_],/s+=>任何空白字符,()=>捕獲
string text = @"public string testMatchObj string s string match ";string pat = @"(/w+)/s+(string)";// Compile the regular expression.Regex r = new Regex(pat, RegexOptions.IgnoreCase);// Match the regular expression pattern against a text string.Match m = r.Match(text);int matchCount = 0;while (m.Success) { Response.Write("Match"+ (++matchCount) + "<br>"); for (int i = 1; i <= 2; i++) { Group g = m.Groups[i]; Response.Write("Group"+i+"='" + g + "'" + "<br>"); CaptureCollection cc = g.Captures; for (int j = 0; j < cc.Count; j++) { Capture c = cc[j]; Response.Write("Capture"+j+"='" + c + "', Position="+c.Index + "<br>"); } } m = m.NextMatch();}
該事例運行結果是:
Match1
Group1='public'
Capture0='public', Position=0
Group2='string'
Capture0='string', Position=7
Match2
Group1='testMatchObj'
Capture0='testMatchObj', Position=14
Group2='string'
Capture0='string', Position=27
Match3
Group1='s'
Capture0='s', Position=34
Group2='string'
Capture0='string', Position=36
事例二:
string x = this.txt.Text;RegexOptions ops = RegexOptions.Multiline;Regex r = new Regex(@"/[(.+?)/]", ops); ///[(.+?)///] @"/[(.+)/](.*?)/[///1/]"//Response.Write(r.IsMatch(x).ToString()+DateTime.Now.ToString());if (r.IsMatch(x)){ x = r.Replace(x, "<$1>"); Response.Write(x.ToString() + DateTime.Now.ToString()); //Console.WriteLine("var x:" + x);//輸出:Live for nothing}else{ Response.Write("false" + DateTime.Now.ToString());}
這個是為了替換"[]"對,把它們換成"<>"
C#中的正則表達式包含在.NET基礎類庫的一個名稱空間下,這個名稱空間就是System.Text.RegularExpressions
。該名稱空間包括8個類,1個枚舉,1個委托。他們分別是:
Capture: 包含一次匹配的結果;
CaptureCollection: Capture的序列;
Group: 一次組記錄的結果,由Capture繼承而來;
GroupCollection:表示捕獲組的集合
Match: 一次表達式的匹配結果,由Group繼承而來;
MatchCollection: Match的一個序列;
MatchEvaluator: 執行替換操作時使用的委托;
Regex:編譯后的表達式的實例。
RegexCompilationInfo:提供編譯器用于將正則表達式編譯為獨立程序集的信息
RegexOptions 提供用于設置正則表達式的枚舉值
Regex類中還包含一些靜態的方法:
Escape: 對字符串中的regex中的轉義符進行轉義;
IsMatch: 如果表達式在字符串中匹配,該方法返回一個布爾值;
Match: 返回Match的實例;
Matches: 返回一系列的Match的方法;
Replace: 用替換字符串替換匹配的表達式;
Split: 返回一系列由表達式決定的字符串;
Unescape:不對字符串中的轉義字符轉義。
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答