Patrick Wolf
Patrick Wolf

Reputation: 2569

Use C# regex to convert casing in a string

how can I convert this string:

bKk_035A_paint-House_V003
to
BKK_035a_paint-House_v003

with a regular expression (e.g. Regex.Replace)?
This regex matches the string:

^(?<Group1>[a-z][a-z0-9]{1,2})_(?<Group2>\d{3}[a-z]{0,2})_(?<Group3>[a-z-]+)_(?<Group4>v\d{3,5})$

Thanks for any help,
Patrick

Upvotes: 3

Views: 4419

Answers (3)

Patrick Wolf
Patrick Wolf

Reputation: 2569

Final code I used

string input = "lAl_058a_068b_COMP_dsj_V001.txt";
string regex = @"^(?<Group1>[a-z][a-z0-9]{1,2})_(?<Group2>\d{3}[a-z]{0,2})_(?<Group3>[a-z-]+)_(?<Group4>v\d{3,5})$";

StringBuilder sb = new StringBuilder(input);
Match m = Regex.Match(input, regex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (m.Success)
{
    Group g;
    g = m.Groups["Group1"];
    sb.Replace(g.Value, g.Value.ToUpper(), g.Index, g.Length);
    g = m.Groups["Group2"];
    sb.Replace(g.Value, g.Value.ToLower(), g.Index, g.Length);
    g = m.Groups["Group4"];
    sb.Replace(g.Value, g.Value.ToLower(), g.Index, g.Length);
}

Thanks for all your comments, Patrick

Upvotes: 0

Vadim
Vadim

Reputation: 21704

Another alternative using Split and Join methods.

    const string input = "bKk_035A_paint-House_V003";
    string[] strParts = input.Split('_');
    strParts[0] = strParts[0].ToUpperInvariant();
    strParts[1] = strParts[1].ToLowerInvariant();
    strParts[3] = strParts[3].ToLowerInvariant();
    string result = String.Join("_", strParts);

Upvotes: 4

John Weldon
John Weldon

Reputation: 40779

the Regex doesn't match the first string...

I assume you want the first 3 chars upper case, and the rest lowercase?

here's a first pass:

const string mod = @"^([a-z][a-z0-9]{1,2})(_\d{3}[a-z]{0,2}_[a-z]+_v{1}\d{3,5})$";
var converted = 
    new Regex(mod, RegexOptions.IgnoreCase)
        .Replace(input1, 
            m => string.Format(
                   "{0}_{1}",
                   m.Groups[1].ToString().ToUpper(),
                   m.Groups[2].ToString().ToLower()
                 )
                );

Upvotes: 5

Related Questions