You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:36:00