正則表達式不僅是驗證工具,更貫穿 .NET 程式設計的底層邏輯:編譯器解析 ASPX 標記、模板引擎置換標記、郵件主題自動生成,本質皆為「依規則處理文字」。掌握正則機制,能讓開發者透視程式碼本質,從容應對複雜字串處理場景。
using System.Text.RegularExpressions;
Regex.IsMatchif (Regex.IsMatch(input, @"^\s*$"))
Console.WriteLine("空白字串");
else
Console.WriteLine("非空白");
// 忽略大小寫
Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase)
Regex.Matchstring firstNumber = Regex.Match(input, @"\d+").Value;
// 多載支援 RegexOptions
Match.Groups// 編號群組
string subject = Regex.Match(mail, @"^Subject:(.*)").Groups[1].Value;
// 命名群組 (推薦,可讀性高)
string subject = Regex.Match(mail, @"^Subject:(?<Sub>.*)").Groups["Sub"].Value;
Regex.Replace// HTML 編碼範例
string encoded = Regex.Replace(html, @"&", "&");
encoded = Regex.Replace(encoded, @"<", "<");
正則引擎回溯機制、貪婪 vs 惰性量詞、效能優化 (預編譯 RegexOptions.Compiled、靜態快取)、平衡群組處理巢狀結構等,將於後續文章詳細解析。推薦經典著作《精通正則表達式》系統建立知識體系。