views:

1105

answers:

3

Hi,

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})$
  • Group1 = uppercase
  • Group2 = lowercase
  • Group3 = unchanged
  • Group4 = lowercase

Thanks for any help,
Patrick

+1  A: 

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()
                 )
                );
John Weldon
After the edits the solution I propose would work by updating the replacement lambda to refer to all 4 groups... I still like string.split better :)
John Weldon
the regex works for me (case insensitive).. the answer is going in the right direction by the way. thanks
Patrick
+4  A: 

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);
Vadim
+1 for less process intensive solution :)
John Weldon
A: 

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

Patrick