How do replace Every UpperCase Letter with Underscore and the Letter in C#? note: unless the character is already proceeded by a underscore.
UPDATE:
For example,
MikeJones
would be turned into
Mike_Jones
But Mike_Jones
would not be turned into
Mike__Jones
Is Regex the best approach? Where do I start with this one?
So you don't want to change the case of the letters! I know you didn't say you did, but some of us assumed it because that question comes up so often. In that case, this regex is all you need:
s = Regex.Replace(s, @"(?<=[a-z])([A-Z])", @"_$1");
Doing the positive lookbehind for a lowercase letter also ensures that you don't add an underscore to the beginning of the string.
Regex sounds best:
string input = "Test_StringForYou";
string replaced = Regex.Replace(input, @"(?<!_)([A-Z])", "_$1");
Console.WriteLine(replaced);
Output: _Test_String_For_You
Be sure to add a using System.Text.RegularExpressions;
Regex.Replace(subject, "([A-Z])", "_$1");
changes The Quick Brown Fox to _The _Quick _Brown _Fox
Is that what you need?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With