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.
}
優勢:僅處理單字,非單字字元(空格、標點)自動保留,無需複雜模式。
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
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 限制只替換第一次。
string text = "myval = 3";
string pattern = @"(\w+)\s*=\s*(.*)\s*$";
Match m = Regex.Match(text, pattern);
// m.Groups[1] = "myval", Groups[2] = "3"
支援等號前後任意空白,值可包含空格。