Regex to truncate trailing zeroes

前端 未结 2 1966
情歌与酒
情歌与酒 2021-01-22 15:45

I\'m trying to construct a single regex (for Java) to truncate trailing zeros past the decimal point. e.g.

  • 50.000 → 50
  • 50.500 → 50.5
  • 50.0500 → 5
2条回答
  •  无人及你
    2021-01-22 16:33

    The best solution could be using built-in language-specific methods for that task.

    If you cannot use them, you may use

    ^(-?\d+)(?:\.0+|(\.\d*?)0+|\.+)?$
    

    And replace with $1$2.

    See the regex demo. Adjust the regex accordingly. Here is the explanation:

    • ^ - start of string
    • (-?\d+) -Group 1 capturing 1 or 0 minus symbols and then 1 or more digits
    • (?:\.0+|(\.\d*?)0+|\.+)? - An optional (matches 1 or 0 times due to the trailing ?) non-capturing group matching 3 alternatives:
      • \.0+ - a decimal point followed with 1+ zeros
      • (\.\d*?)0+ - Group 2 capturing a dot with any 0+ digits but as few as possible and matching 1+ zeros
      • \.+ - (optional branch, you may remove it if not needed) - matches the trailing dot(s)
    • $ - end of string.

    Java demo:

    String s = "50.000\n50\n50.100\n50.040\n50.\n50.000\n50.500\n50\n-5";
    System.out.println(s.replaceAll("(?m)^(-?\\d+)(?:\\.0+|(\\.\\d*?)0+|\\.+)?$", "$1$2"));
    // => [50, 50, 50.1, 50.04, 50, 50, 50.5, 50, -5]
    

提交回复
热议问题