正規表達式提供強大的文字處理能力,從驗證電子郵件地址到解析多行輸入皆適用。可視為功能增強的萬用字元,提供遠超 *、? 的控制力。
.NET Framework 核心類別為 System.Text.RegularExpressions.Regex。
常用於驗證密碼複雜度、電子郵件、電話號碼等格式。Regex.IsMatch 靜態方法可快速判斷字串是否符合模式:
string emailPattern = @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Console.Write("Enter an e-mail address: ");
string emailInput = Console.ReadLine();
bool match = Regex.IsMatch(emailInput, emailPattern);
Console.WriteLine(match ? "E-mail address is valid." : "Supplied input is not a valid e-mail address.");
即使不完全理解模式細節,只要知道其存在即可套用於應用程式驗證。
使用「群組」功能從符合模式的文字中提取子字串。例如從 URL 擷取通訊協定與連接埠:
string urlPattern = @"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/";
Console.Write("Enter a URL for data parsing: ");
string url = Console.ReadLine();
Regex urlExpression = new Regex(urlPattern, RegexOptions.Compiled);
Match urlMatch = urlExpression.Match(url);
Console.WriteLine("The Protocol you entered was " + urlMatch.Groups["proto"].Value);
Console.WriteLine("The Port Number you entered was " + urlMatch.Groups["port"].Value);
若輸入 https://server.com:2100/home.aspx,輸出:
The Protocol you entered was http
The Port Number you entered was :2100
.NET 將字串作為基底類別庫原生組件,提供豐富的比較、操作、格式化方法。StringBuilder 解決字串串接效能問題。正規表達式與 Regex 類別將強大的模式比對能力整合進框架,讓應用程式更健全。