正則表達式可視為一種特定功能的小型程式語言,用於在文本中定位子字串。可快速分析大量文本以尋找特定字元模式、提取/編輯/替換/刪除子字串,或將提取字串加入集合。基本語法請參考「深入淺出正則表達式」系列文章。
System.Text.RegularExpressions 命名空間提供支援類別,主要包括 Regex、MatchCollection、Match、GroupCollection、Group、CaptureCollection、Capture。類別關係圖如下:

使用 Regex.Matches 尋找所有符合模式的字串:
string text = "I've found this amazing URL at https://www.sohu.com ,and then find ftp://FTP.sohu.com is better.";
string pattern = @"\b(\S+)://(\S+)\b";
MatchCollection mc = Regex.Matches(text, pattern);
foreach (Match match in mc)
{
Console.WriteLine(match.ToString());
}
// 輸出:
// https://www.sohu.com
// ftp://FTP.sohu.com
使用具名分組 (?<name>...) 可輕鬆提取子部分:
string pattern = @"\b(?<protocol>\S+)://(?<address>\S+)\b";
MatchCollection mc = Regex.Matches(text, pattern);
foreach (Match match in mc)
{
GroupCollection gc = match.Groups;
string output = "URL:" + match.Value + ";Protocol:" + gc["protocol"].Value + ";Address:" + gc["address"].Value;
Console.WriteLine(output);
}
// 輸出:
// URL:https://www.sohu.com;Protocol:http;Address:www.sohu.com
// URL:ftp://ftp.sohu.com;Protocol:ftp;Address:FTP.sohu.com
Match 代表一次成功的比對,包含完整比對字串與分組集合。Group 代表一個分組的比對結果,GroupCollection 可透過索引或名稱存取。(?<name>...) 大幅提升程式碼可讀性與維護性。