May has well toss this one out. Very simple and worked for me.
public static string ToSnakeCase(this string text)
{
text = Regex.Replace(text, "(.)([A-Z][a-z]+)", "$1_$2");
text = Regex.Replace(text, "([a-z0-9])([A-Z])", "$1_$2");
return text.ToLower();
}
Testing it with some samples (borrowed from @GeekInside's answer):
var samples = new List<string>() { "TestSC", "testSC", "TestSnakeCase", "testSnakeCase", "TestSnakeCase123", "_testSnakeCase123", "test_SC" };
var results = new List<string>() { "test_sc", "test_sc", "test_snake_case", "test_snake_case", "test_snake_case123", "_test_snake_case123", "test_sc" };
for (int i = 0; i < samples.Count; i++)
{
var sample = samples[i];
Console.WriteLine("Test success: " + (sample.ToSnakeCase() == results[i] ? "true" : "false"));
}
Produced the following output:
Test success: true
Test success: true
Test success: true
Test success: true
Test success: true
Test success: true
Test success: true
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems
~Jamie Zawinski – Grip[a-z0-9]
to[a-zA-Z0-9]
regex101.com/r/Otna7T/1 – SiselyLiveKarma
correctly: is theL
really replaced withl
in your tests? – IntermentFOoBAr -> foo_bar -> FooBar
andFooBar ->foo_bar -> FooBar
. I changed to avoid subsequently upper case characters. – Wispy