本文實(shí)例講述了C#正則表達(dá)式匹配與替換字符串功能。分享給大家供大家參考,具體如下:
事例一:\w+=>[A-Za-z1-9_],\s+=>任何空白字符,()=>捕獲
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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(); } |
該事例運(yùn)行結(jié)果是:
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
事例二:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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()); } |
這個(gè)是為了替換"[]"對(duì),把它們換成"<>"
C#中的正則表達(dá)式包含在.NET基礎(chǔ)類庫的一個(gè)名稱空間下,這個(gè)名稱空間就是System.Text.RegularExpressions
。該名稱空間包括8個(gè)類,1個(gè)枚舉,1個(gè)委托。他們分別是:
Capture: 包含一次匹配的結(jié)果;
CaptureCollection: Capture的序列;
Group: 一次組記錄的結(jié)果,由Capture繼承而來;
GroupCollection:表示捕獲組的集合
Match: 一次表達(dá)式的匹配結(jié)果,由Group繼承而來;
MatchCollection: Match的一個(gè)序列;
MatchEvaluator: 執(zhí)行替換操作時(shí)使用的委托;
Regex:編譯后的表達(dá)式的實(shí)例。
RegexCompilationInfo:提供編譯器用于將正則表達(dá)式編譯為獨(dú)立程序集的信息
RegexOptions 提供用于設(shè)置正則表達(dá)式的枚舉值
Regex類中還包含一些靜態(tài)的方法:
Escape: 對(duì)字符串中的regex中的轉(zhuǎn)義符進(jìn)行轉(zhuǎn)義;
IsMatch: 如果表達(dá)式在字符串中匹配,該方法返回一個(gè)布爾值;
Match: 返回Match的實(shí)例;
Matches: 返回一系列的Match的方法;
Replace: 用替換字符串替換匹配的表達(dá)式;
Split: 返回一系列由表達(dá)式?jīng)Q定的字符串;
Unescape:不對(duì)字符串中的轉(zhuǎn)義字符轉(zhuǎn)義。
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。