如何在 C# .NET 中使用正则表达式替换组值
本文关键字:正则表达式 替换 NET | 更新日期: 2023-09-27 18:35:23
我有一个字符串,比如
string s= "I WAS born in AMERICA on december 1978.";
现在我想使用正则表达式将 12 月转换为 12 月
我在下面使用了不完整的正则表达式
s=Regex.Replace(s,(january|february|march|April|may|june|july|august|september|October|november|December),CultreInfo.InvariantCulture.TextInfo.ToTitleCase(?????),RegexOption.IgnoreCase);
我必须在这里写什么(?????),以便我可以得到下面的输出
s= "I WAS born in AMERICA on December 1978.";
还有其他方法可以申请吗?
查看regex.replace
文档,我注意到您必须使用回调函数。
所以写一个函数:
function CustomReplace( Match m ) {
return CultreInfo.InvariantCulture.TextInfo.ToTitleCase(m.Groups[1].Value)
}
并将其作为第三个参数传递:
s = Regex.Replace(
s,
"(january|february|march|April|may|june|july|august|september|October|november|December)",
CustomReplace,
RegexOption.IgnoreCase
);
使用命名捕获和内联匹配评估器:
string s = "I WAS born in AMERICA on december 1978.";
s = Regex.Replace(
s,
"(?<months>january|february|march|April|may|june|july|august|september|October|november|December)",
new MatchEvaluator(
match => CultureInfo
.InvariantCulture
.TextInfo
.ToTitleCase(match.Groups["months"].Value)
),
RegexOptions.IgnoreCase
);