C#正則表達式匹配與替換字符串功能示例
本文實例講述了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: 執(zhí)行替換操作時使用的委托;
Regex:編譯后的表達式的實例。
RegexCompilationInfo:提供編譯器用于將正則表達式編譯為獨立程序集的信息
RegexOptions 提供用于設置正則表達式的枚舉值
Regex類中還包含一些靜態(tài)的方法:
Escape: 對字符串中的regex中的轉義符進行轉義;
IsMatch: 如果表達式在字符串中匹配,該方法返回一個布爾值;
Match: 返回Match的實例;
Matches: 返回一系列的Match的方法;
Replace: 用替換字符串替換匹配的表達式;
Split: 返回一系列由表達式?jīng)Q定的字符串;
Unescape:不對字符串中的轉義字符轉義。
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關于C#相關內(nèi)容感興趣的讀者可查看本站專題:《C#正則表達式用法總結》、《C#編碼操作技巧總結》、《C#中XML文件操作技巧匯總》、《C#常見控件用法教程》、《WinForm控件用法總結》、《C#數(shù)據(jù)結構與算法教程》、《C#面向?qū)ο蟪绦蛟O計入門教程》及《C#程序設計之線程使用技巧總結》
希望本文所述對大家C#程序設計有所幫助。
相關文章
C#創(chuàng)建數(shù)據(jù)庫及附加數(shù)據(jù)庫的操作方法
這篇文章主要介紹了C#創(chuàng)建數(shù)據(jù)庫及附加數(shù)據(jù)庫的操作方法,涉及C#針對數(shù)據(jù)庫常見的創(chuàng)建、添加、連接等操作技巧,需要的朋友可以參考下2016-06-06