简体   繁体   English

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

[英]Java - Regex replace leading zeros, but not all and keep minus

I'm looking for a regex to replace a String to the following (number) format: 我正在寻找将字符串替换为以下(数字)格式的正则表达式:

Input examples: 输入示例:

00000
00440
  235
+3484
-0004
  -00
   +0

Results needed: 需要的结果:

    0
  440
  235
 3484
   -4
    0
    0

I tried to modify the following... just to leave at least + and - and remove the zeros, but I just running in circles. 我试图修改以下内容...仅保留至少+和-并删除零,但我只是绕圈跑。 Can some help me? 可以帮我吗?

input.replaceAll("^(\\+?|-?)0+(?!)", "");

PS: It's optional, that the +0/-0 is shown as 0, but would be a plus. PS:+ 0 / -0显示为0是可选的,但将是加号。

You can use: 您可以使用:

String repl = input.replaceAll("^(?:(-)|\\+)?0*(?!$)", "$1");

RegEx Demo 正则演示

RegEx Breakup: 正则表达式分解:

^       # 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

Alternatively, you can use slightly better performing regex: 另外,您可以使用性能更好的正则表达式:

String repl = input.replaceAll("^(?:0+|[+]0*|(-)0*)(?!$)", "$1");

RegEx Demo 2 RegEx演示2

try this: 尝试这个:

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

after it input will be without 0's and +, but 0 will still remain as 0. input后将没有0和+,但0仍将保持为0。

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

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