https://www.javacodeexamples.com/java-regular-expression-remove-leading-zeros-example/104
Java Regular Expression Remove Leading Zeros Example
This example will show you how to remove leading zeros from the String in Java including using the regular expressions, indexOf and substring methods, Integer wrapper class, charAt method, and apache commons.
How to remove leading zeros from String using the Java Regular Expressions?
Example String object
1
|
String str = "00051700";
|
And the desired output is “51700”. Note that, we want to remove only leading zeros, not the trailing one.
In order to achieve the desired output, a regular expression can be built like given below.
1
|
String strPattern = "^0+";
|
Where the “^” tells to search from the start of the string and 0+ is for one or more zeros. Basically we want to replace all the zeros from start of the string with empty string value thus removing them. Let’s test our newly built expression.
1
2
3
|
String str = "00051700";
String strPattern = "^0+";
System.out.println( "String: " + str.replaceAll(strPattern, "") );
|
Output
1
|
String: 51700
|
Nice, it removed all the zeros from our input String. How about giving it a second run with different input values? This time input value is “000000” and the desired output value is “0”.
1
2
3
|
String str = "000000";
String strPattern = "^0+";
System.out.println( str.replaceAll(strPattern, "") );
|
Output
1
|
String:
|
Oops, that is not what we wanted. We wanted a 0 as the output if the string contained all the zeros. Let’s change our regular expression a bit. This time we are going to search zeros at the start of the string but we want to make sure that if the string contains only zeros then it should return a zero.
1
|
String strPattern = "^0+(?!$)";
|
The first part “^0+” of expression is still the same. We want to match one or more zeros from the start of the string. While the second part “(?!$)” is a negative lookahead expression where “$” means the end of string.
In general terms, Lookahead is like the if condition. Syntax of lookahead is (?expression). The “!” is used as a “not” operator (negative). So together “(?!expression)” forms a negative lookahead.
In our example, the expression “^0+(?!$)” means match one or more zeros if it is not followed by the end of the string. All characters in our string match with the expression till the lookahead condition is being satisfied. The last zero of our string will not match because it is followed by end of the string thus it will be retained.
1
2
3
|
String str = "0000000";
String strPattern = "^0+(?!$)";
System.out.println( "String: " + str.replaceAll(strPattern, "") );
|
Output
1
|
String: 0
|
This expression solves our original problem. Make sure to trim the leading and trailing spaces first from the string using the trim
method. Check out various ways to remove leading and trailing space from String example.
If you don’t want to use a negative lookahead, it can be addressed by adding one if statement in our original pattern like given below.
1
2
3
4
5
6
7
8
|
String str = "0000000";
String strPattern = "^0+";
str = str.trim().replaceAll(strPattern, "");
if(str.equals(""))
str = "0";
System.out.println( "String: " + str);
|
How to remove leading zeros from String without using Java Regular Expressions?
There are several ways we can do that.
1. Using the indexOf and substring methods of the String class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
String sourceString = "000000";
//trim the whitespaces first
sourceString = sourceString.trim();
while(sourceString.indexOf("0") == 0){
sourceString = sourceString.substring(1);
}
/*
* If the source string is empty, make it zero
* Reason: either the original string was empty or
* it contained all zeros
*/
if(sourceString.isEmpty())
sourceString = "0";
System.out.println( "String: " + sourceString);
|
Output
1
|
String: 0
|
If the first character of the string is zero, the while loop condition becomes true and the substring
method will be executed. The sourceString.substring(1) method creates a substring of the original string starting from the index 1 (thus removing the first 0) and assigns it back to the original string. The while loop continues to execute until it finds a non-zero character as the first character of the string thus removing all leading zeros from the string. Here are the String indexOf and String substring examples for the reference.
2) Using the chartAt method of the String class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
String sourceString = "00051700";
//trim the whitespaces first
sourceString = sourceString.trim();
for(int i=0; i < sourceString.length(); i++){
if(sourceString.charAt(i) != '0'){
sourceString = sourceString.substring(i);
break;
}
}
System.out.println( "String: " + sourceString);
|
It loops through the source string until it finds the first non-zero character in the string using the charAt
method, get the substring of the original string from that index and breaks the loop.
This method is more efficient than the indexOf
& substring
approach given above because substring is taken only once when it finds a non-zero character. The indexOf
& substring
approach takes substring once for each leading zero found in the string.
3) Using parseInt() method of the Integer wrapper class
One more simple solution is to use the parseInt
method of the Integer wrapper class.
1
2
3
4
5
6
7
8
9
10
11
|
String sourceString = "00051700";
try{
sourceString = String.valueOf( Integer.parseInt(sourceString) );
}catch(NumberFormatException e){
System.out.println("String does not contain a valid number");
}
System.out.println( "String: " + sourceString);
|
Note: This approach does not work if the source string contains alphanumeric characters or if the string is empty. You can visit Java String to Int example & int to String example for more details.
4) Using Apache Commons
This is the easiest approach among all others, provided if you can use a third-party library. Apache commons StringUtils class provides a very handy method stripStart
that can be used to remove leading zeros from the source string as given below.
1
2
3
4
|
String sourceString = "00051700";
sourceString = StringUtils.stripStart(sourceString, "0");
System.out.println( "String: " + sourceString);
|
This example is a part of the Java RegEx tutorial.
If you think there is a better approach to remove leading zeros from the string which is not covered here, please let me know in the comments section below.