c# string character replace

前端 未结 4 1773
一向
一向 2021-01-14 18:04

I have a string where the third last character is sometimes a , If this is the case I want to replace it with a . The string could also have other

4条回答
  •  执笔经年
    2021-01-14 18:58

    Try this

    System.Text.RegularExpressions.Regex.Replace([the_string], "(,)(.{2})$", ".$2")
    

    It should do it if by 'third last character' you literally mean the third-last character in the whole string.

    That said - you might need to tweak if there are new lines - e.g. add the RegexOptions.Singleline enum as an extra parameter.

    For better performance - probably - you could pre-declare the regex inside a class body:

    static readonly Regex _rxReplace = new Regex("(,)(.{2})$", RegexOptions.Compiled);
    

    Then when you want to use it it's just:

    var fixed = _rxReplace.Replace([the_string], ".$2");
    

提交回复
热议问题