Jamie Jamie - 3 months ago 16
C# Question

Regex - PascalCase to lower case with underscores

I'm trying to convert PascalCase property names such as

Is24Hour
,
Is512
to JSON-style lowercase with underscores (ie.
is_24_hour
,
is_512
) using C#.

So far I've got far but it doesn't work for multiple numbers.

([A-Z])([A-Z0-9][a-z])|([a-z0-9])([A-Z0-9])


With the replacement expression (
$1$3_$2$4
)

For example
"Is24Hour"
becomes
"Is_24_Hour"
(which is then lower-cased by
.ToLower()
).
but
"Is512"
becomes
"Is_51_2"
.

Answer Source

Use String.ToLower for the lowercase.

For the regex, the following seems to work:

((?<=.)[A-Z][a-zA-Z]*)|((?<=[a-zA-Z])\d+)

combined with the replacement expression:

_$1$2

Here's a full sample:

string strRegex = @"((?<=.)[A-Z][a-zA-Z]*)|((?<=[a-zA-Z])\d+)";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline);
string strTargetString = @"Is24Hour" + "\n" + 
    @"Is512" + "\n" + @"A12Hour4" + "\n" + 
    @"23AHourDay12" + "\n" + @"An8DAY512";

string strReplace = @"_$1$2";

return myRegex.Replace(strTargetString, strReplace).ToLower();