skysurfer
skysurfer

Reputation: 873

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

I need to remove the first specific word from a phrase (for instance Write) and return the remaining words with the first capitalized.

Write your letters in the sand => Your letters in the sand

I use this code

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

and I get

test == "your letter in the sand"

but I don't know how to capitalize the second captured group

Upvotes: 1

Views: 375

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use

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

See the C# demo.

Here, ^\w+\W+(\w) matches

  • ^ - start of string
  • \w+ - one or more word chars
  • \W+ - one or more non-word chars
  • (\w) - Group 1: a word char.

The x => x.Groups[1].Value.ToUpper() lambda expression takes the Group 1 value (the first char of the second word) and puts it back into the resulting string in place of matched text, after turning it to upper case.

Upvotes: 2

Related Questions