简体   繁体   中英

How to remove leading zeros from numeric text?

I am using this to remove leading zeros from my input string.

return a.replaceAll("^0+",""); 

But the above string even removes from any string which is alphanumeric as well. I do not want to do that. My requirement is:

Only the leading zeros of numeric numbers should be removed eg

00002827393 -> 2827393

If you have a alpha numeric number the leading zeros must not be removed eg

000ZZ12340 -> 000ZZ12340

You can check if your string is only composed of digits first :

Pattern p = Pattern.compile("^\\d+$");
Matcher m = p.matcher(a);

if(m.matches()){
  return a.replaceAll("^0+", "");
} else {
  return a;
}

Also :

  • consider making your pattern static, that way it will only be created once
  • you may want to isolate the part with the matcher in a smaller function, "isOnlyDigit" for example

You can also try this:

a.replaceAll("^0+(?=\\d+$)", "")

Notice that the positive lookahead (?=\\\\d+$) checks to see that the rest of the string (after the starting 0 s, matched by ^0+ ) is composed of only digits before matching/replacing anything.


System.out.println("00002827393".replaceAll("^0+(?=\\d+$)", ""));
System.out.println("000ZZ12340".replaceAll("^0+(?=\\d+$)", ""));
2827393
000ZZ12340

Test if the incoming string matches the numeric pattern "\\d+". "\\d" is the character class for digits . If it's numeric, then return the result of the call to replaceAll , else just return the original string.

if (str.matches("\\d+"))
    return str.replaceAll("^0+", "");
return str;

Testing:

public static void main (String[] args) throws java.lang.Exception
{
   System.out.println(replaceNumZeroes("0002827393"));
   System.out.println(replaceNumZeroes("000ZZ1234566"));
}

yields the output

2827393
000ZZ1234566

Logic: it will convert the string to char array and start from i=0; As soon as it hits the first the first numeric value it breaks from the for loop and as soon as it hits first character (other than 1 to 9) it returns the same string. After the first for loop we have following cases to consider:

case 1. 00000000000
case 2. 00000011111
case 3. 11111111111

if it's 1 or 3 (ie the i's value from the first for loop will be 0 or length of the string )case then just return the string. Else for the 2nd case copy from the char array to a new char array starting for the i's value (i's value we will get from the first for loop and it holds the first numeric value position.). Hope it clears. 在此输入图像描述

    public String trimLeadingZeros(String str)
    {
    if (str == null)
    {
        return null; //if null return null
    }
    char[] c = str.toCharArray();
    int i = 0;

    for(; i<c.length; i++)
    {
        if(c[i]=='0')
        {
           continue; 
        }
        else if(c[i]>='1' && c[i]<='9')
        {
            break;
        }
        else
        {
            return str;
        }
    }
    if(i==0 || i==c.length)
    {
        return str;
    }
    else
    {
        char[] temp = new char[c.length-i];
        int index = 0;
        for(int j=i; j<c.length; j++)
        {
            temp[index++] = c[j];
        }
        return new String(temp);
    }
    }

Simply I did the following

String string = string.trim();
while(string.charAt(0) == '0'){
    string = string.substring(1);
}

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