Regex是我喜歡的東西,Regex在字串處理方面,除了效能問題外,它有著無可比擬的優勢。C#中引入了Regex的類庫,給我們帶來了很大的方便。
要在C#中使用Regex,需要引用如下的名字空間:
using System.Text;
using System.Text.RegularExpressions;
在C#中使用Regex,最重要的類是Regex。Regex對象的建構函式參數中最常見的一個是Regex的串,另外一個經常使用的是RegexOptions。Regex的字串和Regex的文法這裡就不羅嗦了,大家有興趣的話,可以給我寫郵件和我討論討論。關於RegexOptions,下面是其中一些主要參數的介紹:
RegexOptions.Compiled 讓C#把Regex編譯成一個Assembly,這樣可以在執行正則的時候啟動的更快。這個參數需要注意的事情是,使用這個選項時,Regex一定是靜態字串,而不能使動態字串(可以想象,動態字串是不會有任何效果的)。
RegexOptions.IgnoreCase 讓Regex匹配的時候忽略大小寫。
RegexOptions.Multiline 多行模式正則匹配。
RegexOptions.None 不指定任何的選項。
RegexOptions.RightToLeft 從右向左開始匹配。
RegexOptions.SingleLine 單行模式正則匹配。
下面討論Regex的使用:
Regex token = new Regex(@"((?<protocol>[a-zA-Z]*?)://)?(?<domain>[^/]*)(?<path>.*)", RegexOptions.Compiled);
Match matchList = token.Match("http://www.sina.com.cn/index.html");
if (matchList.Success)
{
Console.WriteLine( "Protocol:{0},Domain:{1},Path:{2}" ,
matchList.Groups["protocol"] ,
matchList.Groups["domain"] ,
matchList.Groups["path"]) ;
}
上面的是匹配單行的情況,下面的例子是示範的匹配多個結果的情況:
Regex token = new Regex(@"\s*((?<protocol>\w*?)://)?(?<domain>[^\/\s]+)(?<path>[^\s]*)", RegexOptions.Compiled);
MatchCollection matches = token.Matches("http://www.sina.com.cn/index.html http://www.microsoft.com ftp://ftp.cav.com/info.zip");
if (matches.Count != 0)
{
foreach (Match matchList in matches)
{
Console.WriteLine("Protocol:{0},Domain:{1},Path:{2}",
matchList.Groups["protocol"],
matchList.Groups["domain"],
matchList.Groups["path"]);
foreach (Capture c in matchList.Captures)
{
Console.WriteLine("Capture:[" + c + "]");
}
}
}
下面是一個Replace的用法,主要目的是為了示範MatchEvaluator.
public static string ReplaceEva(Match match)
{
return match.Groups["protocol"].Value + "://" + "www.google.com/" + match.Groups["path"].Value;
}
Regex token = new Regex(@"\s*((?<protocol>\w*?)://)?(?<domain>[^\/\s]+)(?<path>[^\s]*)", RegexOptions.Compiled);
string strNew = token.Replace("www.sohu.com/index.htm",new MatchEvaluator(ReplaceEva));
Console.WriteLine("New Line:{0}", strNew);
MatchEvaluator是一個函數代理,用來處理替換過程中得到的每一個Match。返回的字串就是替換後的字串。
最後示範以下最簡單的使用正則進行Splite的操作,例子代碼如下:
Regex r = new Regex("(-)");
string[] s = r.Split("one-two-banana");
OK, That's all.希望能夠對大家有所協助。