Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# regex to convert camelCase to Sentence case

Tags:

c#

regex

In my example var key = new CultureInfo("en-GB").TextInfo.(item.Key) produces, 'Camelcase' what regular expression could I add that would produce a space before the second 'c' ?

Examples:

'camelCase' > 'Camel case'

'itIsTimeToStopNow' > 'It is time to stop now'

like image 677
Andy Avatar asked Jan 29 '26 16:01

Andy


2 Answers

One of the ways how you can do it.

string input = "itIsTimeToStopNow";
string output = Regex.Replace(input, @"\p{Lu}", m => " " + m.Value.ToLowerInvariant());
output = char.ToUpperInvariant(output[0]) + output.Substring(1);
like image 123
Ulugbek Umirov Avatar answered Jan 31 '26 06:01

Ulugbek Umirov


One way is to replace capital letters with space capital letters then make the first character uppercase:

var input = "itIsTimeToStopNow";

// add spaces, lower case and turn into a char array so we 
// can manipulate individual characters
var spaced = Regex.Replace(input, @"[A-Z]", " $0").ToLower.ToCharArray();

// spaced = { 'i', 't', ' ', 'i', 's', ' ', ... }

// replace first character with its uppercase equivalent
spaced[0] = spaced[0].ToString().ToUpper()[0];

// spaced = { 'I', 't', ' ', 'i', 's', ' ', ... }

// combine the char[] back into a string
var result = String.Concat(spaced);

// result = "It is time to stop now"
like image 37
dav_i Avatar answered Jan 31 '26 06:01

dav_i



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!