Remove trailing decimal point & zeroes with Regex

前端 未结 3 1156
猫巷女王i
猫巷女王i 2021-02-05 13:22

Is this the proper REGEX to remove trailing decimal and zeroes from a string? I can\'t get it to work. What am I missing?

  1. 78.000 -> 78
  2. 78.008 -> 78.008
相关标签:
3条回答
  • 2021-02-05 14:07

    Nope. Use this:

    str.replaceAll("[.0]+$", "");
    
    0 讨论(0)
  • 2021-02-05 14:14

    Get rid of the ^, which matches the start of the string. You also need to escape ., since it's a regex meta character that matches any character (except newlines):

    str.replaceAll("\\.0*$", "");
    

    Demo: http://ideone.com/RSJrO

    0 讨论(0)
  • 2021-02-05 14:16

    You need to escape the ., as it is a special character in Regex that matches any character. You also have to remove the ^, which anchors at the beginning of the number.

    str.replaceAll("\\.0*$", "");
    

    You can use a lookbehind if you want to make sure there is a number in front of the dot, like this:

    str.replaceAll("(?<=^\\d+)\\.0*$", "");
    

    The lookbehind (the (?<=...) part) is not a part of the match, so it will not be replaced, but it still has to match for the rest of the regex to match.

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