删除字符串内的小数

问题描述 投票:1回答:1

我正在尝试将所有值添加到字符串生成器,以便可以对其进行序列化。因此,我的stringbuilder看起来像

sb = abc78.00xyz

现在,在这里我只想删除小数点后的0,并希望像这样输出

Input       ->  Output I want
abc78.00xyz -> abc78xyz
abc78.08xyz -> abc78.08xyz

我尝试使用正则表达式,但是它不起作用尝试过:

sb.toString().replaceAll("\\.0*$", "")
sb.toString().replaceAll("[.0]+", "")

但是这仅在我有数字的情况下有效。

有人可以告诉我如何获得所需的值吗?

java regex
1个回答
1
投票

您可以使用

s = s.replaceAll("(?<=\\d)\\.0+(?!\\d)", "");

请参见regex demo

详细信息

  • (?<=\d)-当前位置之前,必须有一个数字
  • [\.-点
  • [0+-一个或多个0数字
  • (?!\d)-不跟任何其他数字。

Java demo

List<String> strs = Arrays.asList("abc78.00xyz", "abc78.08xyz");
for (String str : strs) {
    System.out.println( str.replaceAll("(?<=\\d)\\.0+(?!\\d)", "") );
}
// => abc78xyz, abc78.08xyz
© www.soinside.com 2019 - 2024. All rights reserved.