首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 正則表達式 Replace 進階應用:從基礎替換到 MatchEvaluator 複雜轉換

     編輯:關於C語言

前言:Regex.Replace 的兩種範式

System.Text.RegularExpressions.Regex.Replace 是 .NET 中處理字串轉換的核心工具。根據複雜度可分為兩種模式:

  1. 靜態替換: 直接指定替換字串(支援 $1、${name} 等回參考)。
  2. 動態替換: 透過 MatchEvaluator 委派,為每個比對結果執行自訂邏輯回傳替換字串。

掌握兩者差異與適用場景,能大幅簡化字串處理程式碼。

基礎篇:靜態替換與常用模式

1. 簡單字串取代

string input = "abracadabra";
string result = Regex.Replace(input, "abra", "zzzz");
// 結果:zzzzcadzzzz

2. 使用回參考重組字串:去除首尾空白

string input = "   abra   ";
string pattern = @"^\s*(.*?)\s*$";
string result = Regex.Replace(input, pattern, "$1");
// 結果:abra

3. 常用實用模式速查表

用途模式範例輸入替換/結果
移除 C 註解/\*.*?\*/ (搭配 RegexOptions.Singleline)/* 註解 */ code"" → code
統一換行符\r\n|\r混合換行文字\n
HTML 標籤屬性提取<a\s+href=["']([^"']+)["']<a href="x.html">$1 → x.html
IPv4 驗證/擷取(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)192.168.1.1比對成功
檔名去路徑^.*[\\/]C:\path\file.txt"" → file.txt
合併多行為單行\s*\r?\n\s*多行文字" "
提取所有數字\d+\.?\d*|\.\d+test 1, 2.3, .47MatchCollection

進階篇:MatchEvaluator 動態替換

當替換邏輯需根據比對內容動態計算(如大小寫轉換、數學運算、查表替換)時,MatchEvaluator 是最佳選擇。

範例:將句子中每個單字首字母大寫(Title Case)

string input = "the quick red fox jumped over the lazy brown dog.";
string pattern = @"\w+"; // 單字

string result = Regex.Replace(input, pattern, m =>
{
    string word = m.Value;
    return char.ToUpper(word[0]) + word.Substring(1).ToLower();
});
// 結果:The Quick Red Fox Jumped Over The Lazy Brown Dog.

範例:將數字乘以 2

string input = "價格: 10 元, 數量: 5 個";
string result = Regex.Replace(input, @"\d+", m => (int.Parse(m.Value) * 2).ToString());
// 結果:價格: 20 元, 數量: 10 個

範例:條件式替換(僅替換長度 > 3 的單字)

string result = Regex.Replace(input, @"\b\w+\b", m =>
    m.Value.Length > 3 ? m.Value.ToUpper() : m.Value);

深度解析:Group、Capture 與比對引擎細節

理解 Group、Capture、Match 階層關係,有助於撰寫高效能模式:

  • Match:單次比對結果,繼承 Group。
  • Group:一對括號的比對結果,含 Captures 集合。
  • Capture:單一捕獲片段。同一 Group 因量詞重複比對會產生多個 Capture,Group.Value 等於最後一個 Capture.Value。
// 模式:(abra(cad)?)+
// 輸入:abracadabra
// Group 1 (外層) Captures: [0]="abracad", [1]="abra"
// Group 2 (內層) Captures: [0]="cad"
// Group.Value 取最後 Capture → Group1="abra", Group2="cad"

效能與最佳實務指南

  1. 預編譯靜態 Regex: 重複使用的模式宣告為 static readonly Regex,或使用 RegexOptions.Compiled(啟動較慢但執行快)。
  2. 避免災難性回溯: 慎用 .*、.+ 搭配巢狀量詞,改用 .*? 或具體字元類別 [^"]*。
  3. 善用 RegexOptions: IgnoreCase、Singleline (. 匹配換行)、Multiline (^$ 匹配行首尾)、ExplicitCapture (僅命名群組捕獲)。
  4. 大量資料改用非回溯引擎: .NET 7+ 支援 RegexOptions.NonBacktracking,對超長輸入有線性時間保證。
  5. 記憶體管理: MatchCollection 會一次載入所有比對,大量資料改用 Regex.Matches(...).Cast<Match>() 串流處理或迴圈 m.NextMatch()。

結語

Regex.Replace 搭配 MatchEvaluator 是 .NET 字串處理的瑞士刀。從簡單的格式清理到複雜的語義轉換,掌握靜態回參考與動態委派雙重範式,並理解比對引擎的 Group/Capture 機制,能讓你寫出既優雅又高效的字串處理程式碼。下次面對複雜字串轉換需求時,請優先考慮「能否用一行 Regex.Replace 解決?」

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved