正则表达式截断尾随零 [英] Regex to truncate trailing zeroes
问题描述
我正在尝试构造一个单一的正则表达式(用于Java)来截断小数点后面的尾随零。例如
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→50.05
- -5→-5
- 50→50
- 5.5→5.5
- 50.000 → 50
- 50.500 → 50.5
- 50.0500 → 50.05
- -5 → -5
- 50 → 50
- 5.5 → 5.5
想法是以尽可能紧凑的形式表示实数(或整数)。
Idea is to represent the real number (or integer) in the most compact form possible.
这是我构建的内容:
^(-?[.0-9]+?)\.?0+$
我正在使用 $ 1
捕获截断的数字字符串。
I'm using $1
to capture the truncated number string.
上述模式的问题是50被截断为5.我需要某种方式来表达 0 +
必须遵循。
(小数点)。
我尝试过使用负面背后,但不能得到任何匹配。
The problem with the pattern above is that 50 gets truncated to 5. I need some way to express that the 0+
must follow a .
(decimal point).
I've tried using negative-behind, but couldn't get any matches.
推荐答案
最好的解决方案可能是使用内置语言特定的方法来完成该任务。
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+|\.+)?$
并替换为 $ 1 $ 2
。
请参阅正则表达式演示。相应地调整正则表达式。以下是解释:
See the regex demo. Adjust the regex accordingly. Here is the explanation:
-
^
- 字符串开头 -
( - ?\d +)
-Group 1捕获1或0减号然后1位或更多位数 -
(?:\ + + +((\。\ n *?)0+ | \。+)?
- 可选(匹配1或0次,因为尾随?
)非捕获组匹配3个替代方案:
-
\.0 + +
- 小数点后跟1+零 -
(\\ \\d *?)0 +
- 第2组捕获任意0位以上的点,但尽可能少且匹配1+个零 -
\。+
- (可选分支,如果不需要,可以将其删除) - 匹配尾随点
^
- 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)
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]
这篇关于正则表达式截断尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-