Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert camel case to snake case with two capitals next to each other

Tags:

c#

regex

I am trying to convert camel case to snake case.

Like this:

"LiveKarma" -> "live_karma"
"youGO" -> "you_g_o"

I cannot seem to get the second example working like that. It always outputs as 'you_go' . How can I get it to output 'you_g_o'

My code:

(Regex.Replace(line, "(?<=[a-z0-9])[A-Z]", "_$0", RegexOptions.Compiled)).ToLowerInvariant()
like image 598
Live Karma Avatar asked Jul 23 '20 13:07

Live Karma


People also ask

How do you convert a camel case to a snake case in python?

What would be a good way to convert from snake case ( my_string ) to lower camel case (myString) in Python 2.7? The obvious solution is to split by underscore, capitalize each word except the first one and join back together.

How do you make a snake case?

Snake case (or snake_case) is the process of writing compound words so that the words are separated with an underscore symbol (_) instead of a space. The first letter is usually changed to lowercase. Some examples of Snake case would be "foo_bar" or "hello_world".


1 Answers

Here is an extension method that transforms the text into a snake case:

using System.Text;

public static string ToSnakeCase(this string text)
{
    if(text == null) {
        throw new ArgumentNullException(nameof(text));
    }
    if(text.Length < 2) {
        return text;
    }
    var sb = new StringBuilder();
    sb.Append(char.ToLowerInvariant(text[0]));
    for(int i = 1; i < text.Length; ++i) {
        char c = text[i];
        if(char.IsUpper(c)) {
            sb.Append('_');
            sb.Append(char.ToLowerInvariant(c));
        } else {
            sb.Append(c);
        }
    }
    return sb.ToString();
}

Put it into a static class somewhere (named for example StringExtensions) and use it like this:

string text = "LiveKarma";
string snakeCaseText = text.ToSnakeCase();
// snakeCaseText => "live_karma"
like image 54
GregorMohorko Avatar answered Dec 02 '22 19:12

GregorMohorko