从字符串中的数字部分删除所有前导零

3
我正在尝试从字符串的数字部分中移除所有前导零。我想出了以下代码。从给定的示例可以看出它起作用。但是,当我在开头添加一个'0'时,它将无法给出正确的输出。有人知道如何实现吗?提前致谢。
输入:(2016)abc00701def00019z -> 输出:(2016)abc701def19z -> 结果:正确
输入:0(2016)abc00701def00019z -> 输出:(2016)abc71def19z -> 结果:错误 -> 期望输出:(2016)abc701def19z
编辑:该字符串可能包含英文字母以外的字符。
String localReference = "(2016)abc00701def00019z";
String localReference1 = localReference.replaceAll("[^0-9]+", " ");
List<String> lists =  Arrays.asList(localReference1.trim().split(" "));
System.out.println(lists.toString());
String[] replacedString = new String[5];
String[] searchedString = new String[5];
int counter = 0;
for (String list : lists) {
   String s = CharMatcher.is('0').trimLeadingFrom(list);
   replacedString[counter] = s;
   searchedString[counter++] = list;

   System.out.println(String.format("Search: %s, replace: %s", list,s));
}
System.out.println(StringUtils.replaceEach(localReference, searchedString, replacedString));

我敢打赌这里有一个正则表达式可以解决,但你也可以将所有数字取出并转换为整数。这将删除所有前导零。然后你只需要用新值替换旧值即可。 - XtremeBaumer
@XtremeBaumer 但是对于太大以至于int无法容纳的数字序列,这种方法会失败。 - Sentry
@Sentry 不确定,但是也许 BigInteger 会删除前导零。我怀疑你是否有一个包含数字的字符串来重载 BigInteger。 - XtremeBaumer
可能是如何从字母数字文本中删除前导零?的重复问题。这个有帮助吗? - Chetan Kinger
@XtremeBaumer 谢谢。我会尝试使用正则表达式。 - Deb
显示剩余2条评论
3个回答

3
str.replaceAll("(^|[^0-9])0+", "$1");

这将删除在非数字字符和字符串开头之后的任何零行。


0
Java有\P{Alpha}+,它匹配任何非字母字符并删除起始的零。
String stringToSearch = "0(2016)abc00701def00019z"; 
Pattern p1 = Pattern.compile("\\P{Alpha}+");
Matcher m = p1.matcher(stringToSearch);
StringBuffer sb = new StringBuffer();
while(m.find()){
    m.appendReplacement(sb,m.group().replaceAll("\\b0+",""));
}
m.appendTail(sb);
System.out.println(sb.toString());

output:

(2016)abc701def19z

感谢您的回复。但是如果字符串包含英文字母以外的内容,这种方法将失败。 - Deb

0

我尝试使用正则表达式完成任务,并根据您提供的两个测试用例成功完成了所需操作。在下面的代码中,$1和$2是前面正则表达式中括号内的部分。

请查看以下代码:

    public class Demo {

        public static void main(String[] args) {

            String str = "0(2016)abc00701def00019z";

/*Below line replaces all 0's which come after any a-z or A-Z and which have any number after them from 1-9. */
            str = str.replaceAll("([a-zA-Z]+)0+([1-9]+)", "$1$2");
            //Below line only replace the 0's coming in the start of the string
            str = str.replaceAll("^0+","");
            System.out.println(str);
        }
    }

谢谢您的回复。但是,如果字符串中包含英文字母以外的字符,这种方法将失败。 - Deb
你还有哪些元素? - Mohit
我也有中文字符而不是英文。 - Deb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接