[英]Java - Regex replace leading zeros, but not all and keep minus
我正在尋找將字符串替換為以下(數字)格式的正則表達式:
輸入示例:
00000
00440
235
+3484
-0004
-00
+0
需要的結果:
0
440
235
3484
-4
0
0
我試圖修改以下內容...僅保留至少+和-並刪除零,但我只是繞圈跑。 可以幫我嗎?
input.replaceAll("^(\\+?|-?)0+(?!)", "");
PS:+ 0 / -0顯示為0是可選的,但將是加號。
您可以使用:
String repl = input.replaceAll("^(?:(-)|\\+)?0*(?!$)", "$1");
正則表達式分解:
^ # line start
(?: # start non-capturing group
(-) # match - and group it in captured group #1
| # OR
\\+ # match literal +
)? # end of optional group
0* # match 0 or more zeroes
(?!$) # negative lookahead to assert we are not at end of line
另外,您可以使用性能更好的正則表達式:
String repl = input.replaceAll("^(?:0+|[+]0*|(-)0*)(?!$)", "$1");
嘗試這個:
length = input.length();
for(int i = 0; i<length; i++) {
if(input.charAt(0) == '0' || input.charAt(0) == '+' ) {
if(input.length() == 1) {
continue;
}
input = input.substring(i+1);
length -= 1;
i -= 1;
}
}
input
后將沒有0和+,但0仍將保持為0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.