我有像這樣的字符串1) "CAP07560" 2) "CAP41060" 3) "CAP43500"4) "CAP22390"我想首先刪除"CAP"字符串中的文本,然后對于剩余的字符串,我想刪除最后一個“0”并刪除字符串開頭的任何零。所以我的輸出將是:1) "756" 2) "4106" 3) "4350"4) "2239"我嘗試了以下方法-public class RegexTest { public static void main(String[] args) { // drop the last "0" and then drop any // zeros at the start of the remaining number. String str = "CAP07560"; String pattern = "^CAP[ 0]*|( |(?<!\\d))*$"; str = str.replaceAll(pattern, ""); System.out.println(str); }}我的輸出:7560所以我的輸出是7560但它應該是756。
1 回答

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
您可以使用交替在單次調用中執行此操作replaceAll
:
str = str.replacAll("^CAP0*|0$", "");
正則表達式詳細信息:
^CAP0*
: 匹配CAP
開頭有 0 個或多個零|
: 或者0$
:匹配最后一個零
添加回答
舉報
0/150
提交
取消