简体   繁体   English

正则表达式用于删除十进制字符串中的零

[英]regex for removing zeros in decimal string

I need to remove zeros from decimal string eg: 007.004(100.007) should be transformed to 7.4(100.7) 我需要从十进制字符串中删除零,例如:007.004(100.007)应该转换为7.4(100.7)

I tried using a matcher based on the pattern "0+(\\d)": 我尝试使用基于模式“ 0 +(\\ d)”的匹配器:

Pattern p = Pattern.compile(regex);
Matcher m = null;
try {

    m = p.matcher(version);
    while (m.find()) {
        System.out.println("Group : " + m.group());
        System.out.println("Group 1 : " + m.group(1));
        version = version.replaceFirst(m.group(), m.group(1));
        System.out.println("Version: " + version);
    }

but this results in 7.4(10.7). 但这得出7.4(10.7)。 Any thoughts on this ? 有什么想法吗?

You need to do a replacement with this pattern: 您需要使用以下模式进行替换:

(\\([^)]+\\))|0+

and this replacement string 和这个替换字符串

\\1 

In other words, you need to capture all that is between parenthesis first and then looking for zeros. 换句话说,您需要先捕获括号之间的所有内容,然后再寻找零。 use the replaceAll method. 使用replaceAll方法。

If you are trying to remove leading zeroes before a nonzero digit, then you can match such runs with this pattern: "(?<!\\\\d)0+(?=[1-9])" . 如果您要删除非零数字之前的前导零,则可以使用以下模式匹配此类运行: "(?<!\\\\d)0+(?=[1-9])" That even uses a zero-length lookahead, as your tags suggest you might have wanted to do. 这甚至会使用零长度的超前查询,因为您的标签显示您可能想这样做。 It would be simpler to use than yours, too, because it doesn't match anything you want to keep: 它也将比您的使用起来更简单,因为它与您想要保留的任何内容都不匹配:

Pattern p = Pattern.compile("(?<!\\d)0+(?=[1-9])");
Matcher m = p.matcher(version);;

version = matcher.replaceAll("");

If you're only going to do this once, then you can simplify to a one-liner: 如果只执行一次,则可以简化为单一格式:

version = version.replaceAll("(?<!\\d)0+(?=[1-9])", "");

There is no need to perform a replacement in another string while matching another: 匹配另一个字符串时,无需在另一个字符串中执行替换:

while (m.find()) {
version = version.replaceFirst(m.group(), m.group(1));

You can instead use this replacement: 您可以改用以下替代方法:

version = version.replaceAll("(^|\\.)0+", "$1");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM