简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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