繁体   English   中英

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

[英]Remove all the leading zero from the number part of a string

我正在尝试从字符串的数字部分中删除所有前导零。 我想出了下面的代码。 从给定的示例,它起作用了。 但是,当我在开头添加“ 0”时,它不会给出正确的输出。 有人知道如何实现吗? 提前致谢

输入:(2016)abc00701def00019z->输出:(2016)abc701def19z-> resut:正确

输入: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));
str.replaceAll("(^|[^0-9])0+", "$1");

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

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

我尝试使用Regex执行任务,并且能够根据您给出的两个测试用例完成所需的任务。 以下代码中的$ 1和$ 2也是前一个Regex中()括号中的部分。

请在下面找到代码:

    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);
        }
    }

暂无
暂无

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

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