有人可以简化以下模式的行: 以下代码正在删除尾随零,但我无法理解它。
字符串阈值为 299.0,输出为 299。
public static String removeTrailingZeros(String threshold) {
Pattern thresholdPattern = Pattern.compile("([\\.,]0)($|\\s+)");
Matcher match = thresholdPattern.matcher(threshold);
threshold = match.replaceFirst("$2");
return threshold;
}
为什么我们要做“match.replaceFirst("$2");” 我无法理解它的意义。
它是如何找到尾随零的?
它不会用 299 替换 299.00 吗?如果我想这样做,我该怎么做才能同时容纳 299.0 和 299.00?
最佳答案
正则表达式替换中的
$1, $2... $n 是对括在括号中的匹配项的引用。 $0 将是整个匹配,$1 将是第一个带括号的捕获,$2 将是第二个,依此类推。
Pattern thresholdPattern = Pattern.compile("([\\.,]0*)($|\\s+)");
它将删除任意数量的尾随零。
关于java - 无法理解 Java 中的模式匹配器示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47966084/