5

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 e.g.

00002827393 -> 2827393

If you have a alpha numeric number the leading zeros must not be removed e.g.

000ZZ12340 -> 000ZZ12340
Harish
  • 59
  • 1
  • 1
  • 2
  • 1
    @syb0rg That's not quite the same. In that post zeros were removed from all alphanumeric strings. Here they're only removed from numbers. – John Kugelman Apr 08 '13 at 22:10
  • Clarification Requested: Alphanumeric characters can be anywhere in string or just after leading zeros? – aartist Apr 08 '13 at 22:10
  • @Harish You are not able to find an answer for this question till now? – Trying Apr 13 '13 at 22:56
  • See [this](http://stackoverflow.com/questions/2800739/how-to-remove-leading-zeros-from-alphanumeric-text) – dARKpRINCE Oct 21 '15 at 15:30

5 Answers5

10

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
Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59
vptheron
  • 7,426
  • 25
  • 34
7

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 0s, 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
arshajii
  • 127,459
  • 24
  • 238
  • 287
4

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
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

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 (i.e. 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. enter image description here

    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);
    }
    }
Trying
  • 14,004
  • 9
  • 70
  • 110
0

Simply I did the following

String string = string.trim();
while(string.charAt(0) == '0'){
    string = string.substring(1);
}
Tharaka
  • 2,883
  • 1
  • 21
  • 13
  • 1
    1. You missed the part that "If you have a alpha numeric number the leading zeros must not be removed". 2. If your string have 20 leading zeros, you will create 20 strings that needs to be garbage collected. – stenix Sep 01 '15 at 08:51