Saturday, October 6, 2012

Java - removing leading zeroes from a string

 
Using Regular Expressions (regex)
String str = "00938";
System.out.println("*" + str.replaceFirst("^0+", "") + "*");
//*938*

Suppose the string contains only zeroes, then the output will be a null string. 
String str = "0000000";
System.out.println("*" + str.replaceFirst("^0+", "") + "*"); 
//**

If you want a zero to remain in the above case use another form -
String str = "0000000";
System.out.println("*" + str.replaceFirst("^0+(?!$)", "") + "*"); 
//*0*

The negative lookahead (?!$) ensures that the entire string is not matched with the regular expression ^0+.
The anchor ^ makes sure that the beginning of the input is matched. 0+ denotes zero or more zeroes (0s).

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *