下面就來研究C#中的Regex,C#中的Regex包含在.NET基礎雷庫的一個名稱空間下,這個名稱空間就是System.Text.RegularExpressions。該名稱空間包括8個類,1個枚舉,1個委託。他們分別是:
Capture: 包含一次匹配的結果;
CaptureCollection: Capture的序列;
Group: 一次組記錄的結果,由Capture繼承而來;
GroupCollection:表示擷取的群組的集合
Match: 一次運算式的匹配結果,由Group繼承而來;
MatchCollection: Match的一個序列;
MatchEvaluator: 執行替換操作時使用的委託;
Regex:編譯後的運算式的執行個體。
RegexCompilationInfo:提供編譯器用於將Regex編譯為獨立程式集的資訊
RegexOptions 提供用於設定Regex的枚舉值
Regex類中還包含一些靜態方法:
Escape: 對字串中的regex中的轉義符進行轉義;
IsMatch: 如果運算式在字串中匹配,該方法返回一個布爾值;
Match: 返回Match的執行個體;
Matches: 返回一系列的Match的方法;
Replace: 用替換字串替換匹配的運算式;
Split: 返回一系列由運算式決定的字串;
Unescape:不對字串中的逸出字元轉義。
首先從使用Regex、Match類的簡單運算式開始學習:
Code
Regex emailregex = new Regex("(?<user>[^@]+)@(?<host>.+)");
String s = "johndoe@tempuri.org";
Match m = emailregex.Match(s);
if ( m.Success )
{
System.Console.WriteLine("User: " + m.Groups["user"].Value);
System.Console.WriteLine("Host: " + m.Groups["host"].Value);
}
else
{
System.Console.WriteLine(s + " is not a valid email address");
}
IsMatch方法指示 Regex 建構函式中指定的Regex在輸入字串中是否找到匹配項。這是我們使用C#Regex時最常用的方法之一。下面的例子說明了IsMatch方法的使用:
Code
Regex emailregex = new Regex("(?<user>[^@]+)@(?<host>.+)");
if(emailregex.IsMatch("ddd*.com"))
{
System.Console.WriteLine("Matched successfully");
}
else
{
System.Console.WriteLine("Matched failed");
}
System.Console.ReadLine();
Split方法是把由Regex匹配項定義的位置將輸入字串拆分為一個子字串數組。例如:
Code
Regex r = new Regex("-"); // Split on hyphens.
string[] s = r.Split("first-second-third");
for(int i=0;i<s.Length;i++)
{
Response.Write(s[i]+"<br>");
}
執行的結果是:
First
Second
Third
看上去和String的Split方法一樣,但string的Split方法在由Regex而不是一組字元確定的分隔字元處拆分字串。
Match方法是在輸入字串中搜尋Regex的匹配項,並Regex 類的 Match 方法返回 Match 對象,Match 類表示Regex匹配操作的結果。下面的例子示範Match方法的使用,並利用Match對象的Group屬性返回Group對象:
Code
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