我有一个字符串 "123.0"
并使用 "123.0".matches( "(\\.)?0*$")
检查它是否有任何尾随零但不匹配。相同的正则表达式正确匹配字符串@ http://regexpal.com/
如果我只想用其他内容替换最后一个零怎么样? String.replace 说:
replace(CharSequence target, CharSequence replacement) - Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
但是 "123.0".replace( "(\\.)?0*$", "")
它不会替换最后一个“.0”。
最佳答案
java.lang.String.matches
方法匹配整个字符串,而不是其中的一部分。 (无需指定 ^
和 $
)。
所以你的模式字符串应该是:
"\\d+\\.?0*"
更新根据问题编辑:
您应该使用replaceAll
而不是替换
。 replace
不接受正则表达式。它按字面解释第一个参数。
"123.0".replaceAll("\\.0*$", "")
关于Java string.match/string.replace 无法正确匹配正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21129998/