Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove leading zeros from numeric text?

Tags:

java

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
like image 411
Harish Avatar asked Apr 08 '13 22:04

Harish


People also ask

How do I remove zeros at the start of a number in Excel?

Method 1 Format cells as number formatting Select the range you want to type number without showing leading zeros, and right click to click Format Cells to open Format Cells dialog, and select Number from the Category pane, then click OK. Note: This method cannot work if you format cells after typing number.


3 Answers

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
like image 162
vptheron Avatar answered Nov 01 '22 14:11

vptheron


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
like image 27
arshajii Avatar answered Nov 01 '22 14:11

arshajii


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
like image 4
rgettman Avatar answered Nov 01 '22 15:11

rgettman