Use C# regex to convert casing in a string

后端 未结 3 345
再見小時候
再見小時候 2021-01-21 07:19

how can I convert this string:

bKk_035A_paint-House_V003
to
BKK_035a_paint-House_v003

with a regular expression (e.g. Regex.R

3条回答
  •  醉话见心
    2021-01-21 08:16

    Final code I used

    string input = "lAl_058a_068b_COMP_dsj_V001.txt";
    string regex = @"^(?[a-z][a-z0-9]{1,2})_(?\d{3}[a-z]{0,2})_(?[a-z-]+)_(?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

提交回复
热议问题