【问题标题】:Regex to remove first word and capitalize the first char of the second with c#正则表达式删除第一个单词并使用 c# 将第二个单词的第一个字符大写
【发布时间】:2021-11-27 16:47:35
【问题描述】:

我需要从短语中删除第一个特定单词(例如 Write)并返回剩余的单词,第一个大写。

把你的信写在沙子里=>你的信在沙子里

我用这个代码

var test = Regex.Replace("Write your letter in the sand", "(^Write )(.)", "$2");

我明白了

test == "your letter in the sand"

但我不知道如何将第二个捕获的组大写

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    你可以使用

    var text = "Write your letter in the sand";
    var test = Regex.Replace(text, @"^\w+\W+(\w)", x => x.Groups[1].Value.ToUpper());
    

    请参阅C# demo

    这里,^\w+\W+(\w) 匹配

    • ^ - 字符串开头
    • \w+ - 一个或多个单词字符
    • \W+ - 一个或多个非单词字符
    • (\w) - 第 1 组:一个单词字符。

    x => x.Groups[1].Value.ToUpper() lambda 表达式将 Group 1 值(第二个单词的第一个字符)转换为大写后将其放回到结果字符串中以代替匹配的文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      相关资源
      最近更新 更多