簡體   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