Skip to content
Advertisement

removes leading zeroes, but leaves one necessary From String in Java

Given:

a = 00099999325
b = 1254

How do I remove leading zeros but leaves one necessary

This is the output I’m expecting:

099999325
1254

Currently, am using this function but i need to optimize it :

//removes leading zeroes, but leaves one if necessary
public static String removeLeadingZeroes(String s) {

    return s.replaceFirst("^0+(?!$)", "");

}

can anyone help me please ? thank you for advanced

Advertisement

Answer

You can use this regex ^0*(0d+) like this:

return s.replaceFirst("^0*(0\d+)", "$1");

I/O

000099999325 -> 099999325
1254         -> 1254
1230004      -> 1230004
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement