Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Replace Every UpperCase Letter with Underscore and the Letter

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?

like image 220
BuddyJoe Avatar asked Mar 08 '10 18:03

BuddyJoe


3 Answers

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.

like image 33
Alan Moore Avatar answered Nov 02 '22 07:11

Alan Moore


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;

like image 106
Jake Avatar answered Nov 02 '22 08:11

Jake


Regex.Replace(subject, "([A-Z])", "_$1");

changes The Quick Brown Fox to _The _Quick _Brown _Fox

Is that what you need?

like image 1
Martin Smith Avatar answered Nov 02 '22 07:11

Martin Smith