Regular expression replace in C#

前端 未结 3 1788
清酒与你
清酒与你 2020-12-30 18:59

I\'m fairly new to using regular expressions, and, based on a few tutorials I\'ve read, I\'m unable to get this step in my Regex.Replace formatted properly.

Here\'s

相关标签:
3条回答
  • 2020-12-30 19:39

    You can do it this with two replace's

    //let stw be "John Smith $100,000.00 M"
    
    sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
    //sb_trim becomes "John Smith,100,000.00,M"
    
    sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
    //sb_trim becomes "John Smith,100000,M"
    
    sw.WriteLine(sb_trim);
    
    0 讨论(0)
  • 2020-12-30 19:42

    Try this::

    sb_trim = Regex.Replace(stw, @"(\D+)\s+\$([\d,]+)\.\d+\s+(.)",
        m => string.Format(
            "{0},{1},{2}",
            m.Groups[1].Value,
            m.Groups[2].Value.Replace(",", string.Empty),
            m.Groups[3].Value));
    

    This is about as clean an answer as you'll get, at least with regexes.

    • (\D+): First capture group. One or more non-digit characters.
    • \s+\$: One or more spacing characters, then a literal dollar sign ($).
    • ([\d,]+): Second capture group. One or more digits and/or commas.
    • \.\d+: Decimal point, then at least one digit.
    • \s+: One or more spacing characters.
    • (.): Third capture group. Any non-line-breaking character.

    The second capture group additionally needs to have its commas stripped. You could do this with another regex, but it's really unnecessary and bad for performance. This is why we need to use a lambda expression and string format to piece together the replacement. If it weren't for that, we could just use this as the replacement, in place of the lambda expression:

    "$1,$2,$3"
    
    0 讨论(0)
  • 2020-12-30 19:57

    Add the following 2 lines

    var regex = new Regex(Regex.Escape(","));
    sb_trim = regex.Replace(sb_trim, " ", 1);
    

    If sb_trim= John,Smith,100000,M the above code will return "John Smith,100000,M"

    0 讨论(0)
提交回复
热议问题