繁体   English   中英

Java-正则表达式替换前导零,但不是全部替换并保持减号

[英]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");

RegEx演示2

尝试这个:

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.

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