簡體   English   中英

正則表達式刪除第一個單詞並將第二個單詞的第一個字符大寫為 c#

[英]Regex to remove first word and capitalize the first char of the second with c#

我需要從短語中刪除第一個特定單詞(例如 Write),並返回首字母大寫的剩余單詞。

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

我用這段代碼

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

我得到

test == "your letter in the sand"

但我不知道如何利用第二個捕獲的組

您可以使用

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

請參閱C# 演示

在這里, ^\w+\W+(\w)匹配

  • ^ - 字符串的開始
  • \w+ - 一個或多個單詞字符
  • \W+ - 一個或多個非單詞字符
  • (\w) - 第 1 組:一個字符字符。

x => x.Groups[1].Value.ToUpper() lambda 表達式采用第 1 組值(第二個單詞的第一個字符)並將其放回結果字符串中以代替匹配的文本,將其轉換為大寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM