C#使用正则移除首个指定单词并将剩余内容首字母大写的实现方法
解决方案
你原来的写法只能原样输出捕获到的小写首字符,C# 正则的替换字符串没有内置大小写转换的标记,需要使用带MatchEvaluator委托的Regex.Replace重载方法实现需求,参考代码如下:
using System.Text.RegularExpressions; string input = "Write your letters in the sand"; string result = Regex.Replace(input, @"^Write\s(.)(.*)$", match => { // 首字符转大写后拼接剩余内容 return match.Groups[1].Value.ToUpper() + match.Groups[2].Value; });
运行后result的值就是目标结果Your letters in the sand。
如果需要移除的首单词可动态配置,可以调整为动态正则的写法:
string removeWord = "Write"; string input = "Write your letters in the sand"; string result = Regex.Replace(input, $@"^{removeWord}\s(.)(.*)$", match => { return match.Groups[1].Value.ToUpper() + match.Groups[2].Value; });
内容的提问来源于stack exchange,提问作者skysurfer
相关产品推荐
相关产品推荐

