views:

545

answers:

5

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?

+8  A: 

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;

Jake
+1 for handling the existing preceding underscore correctly.
Ahmad Mageed
Hadn't noticed that caveat!
Martin Smith
+1 - is there a way to alter the Regex so the first letter has no underscore in front?
tyndall
@tyndall: `(?<!_|^)([A-Z])` or maybe `(?<=[a-z])([A-Z])` should do it.
Alan Moore
+1 I ought to learn those RegularExpression some day! lol
Will Marcouiller
+1  A: 
Regex.Replace(subject, "([A-Z])", "_$1");

changes The Quick Brown Fox to _The _Quick _Brown _Fox

Is that what you need?

Martin Smith
A: 

If you're looking to transform this:

Sample Text

Into

_sample _text

Then no, RegEx won't strictly do that, as you can't transform captures or groups in the replacement expression. You could, of course, use Jake's answer and add a .ToLower() call to the end, which would replace all capital letters with lowercase letters.

If all you're looking to do is prepend an underscore to every capital letter that doesn't already have one, then Jake's answer alone should do the trick.

Adam Robinson
Wrong. You can (http://msdn.microsoft.com/en-us/library/cft8645c%28VS.80%29.aspx).
KennyTM
@Kenny: It's not wrong, as the RegEx syntax doesn't allow for transformations. The *API* does, in this case, but not the syntax itself. For this example, I think calling `ToLower()` is likely to result in clearer, simpler code.
Adam Robinson
@Adam: Then the RegEx syntax doesn't allow replacement either. But I agree scanning the string and use `.ToLower()` is much better than RegEx in this case.
KennyTM
A: 

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, 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.

Alan Moore
A: 

using System.Text.RegularExpressions;

//-----------------------------------------------------------------

string str = Regex.Replace("MyString", @"([A-Z])", " $1").Trim();

//-----------------------------------------------------------------

str givs "My String"

It's working nice

-Md. Rashedul Hasan

Md. Rashedul Hasan