开发者

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开发者_StackOverflow into

Mike__Jones

Is Regex the best approach? Where do I start with this one?


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;


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.Replace(subject, "([A-Z])", "_$1");

changes The Quick Brown Fox to _The _Quick _Brown _Fox

Is that what you need?


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.


Dont know if this is still relevent, but here is a simple way to do it.

private string StripInput(string input)
    {
        var output = input
            .Replace(" ", "_")
            .ToLower().Trim();
        return output;
    }

string TEST = "Hello World";
    litTest.Text = StripInput(TEST);

Will come out as: hello_world


using System.Text.RegularExpressions;

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

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

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

str givs "My String"

It's working nice

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜