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
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.
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 :
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With