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

C# 正則表達式深度解析(五):MatchEvaluator 進階替換與經典模式集

     編輯:關於C語言

MatchEvaluator 自訂替換邏輯

Regex.Replace 可接受 MatchEvaluator 委派,對每個匹配執行自訂邏輯。範例:將文章中每個單字首字母大寫。

static string CapText(Match m) {
    string x = m.Value;
    if (char.IsLower(x[0])) return char.ToUpper(x[0]) + x.Substring(1);
    return x;
}
static void Main() {
    string text = "the quick red fox jumped over the lazy brown dog.";
    string pattern = @"\w+"; // 匹配單字
    string result = Regex.Replace(text, pattern, new MatchEvaluator(CapText));
    Console.WriteLine(result); // The Quick Red Fox Jumped Over The Lazy Brown Dog.
}

優勢:僅處理單字,非單字字元(空格、標點)自動保留,無需複雜模式。

實用經典正則模式速查

1. 羅馬數字驗證

string pattern = @"^M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$";
Regex.Match("vii", pattern).Success; // true

2. 交換前兩個單字

string text = "the quick brown fox";
string pattern = @"(\S+)(\s+)(\S+)";
string result = new Regex(pattern).Replace(text, "$3$2$1", 1);
// 結果:"quick the brown fox"

使用反向參考 $3$2$1 重組,1 限制只替換第一次。

3. 鍵值對解析(Key=Value)

string text = "myval = 3";
string pattern = @"(\w+)\s*=\s*(.*)\s*$";
Match m = Regex.Match(text, pattern);
// m.Groups[1] = "myval", Groups[2] = "3"

支援等號前後任意空白,值可包含空格。

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