I have numbers like this that need leading zero\'s removed.
Here is what I need:
00000004334300343
-> 4334300343
000
You're almost there. You just need quantifier:
str = str.replaceAll("^0+", "");
It replaces 1 or more occurrences of 0 (that is what +
quantifier is for. Similarly, we have *
quantifier, which means 0 or more), at the beginning of the string (that's given by caret - ^
), with empty string.
The correct regex to strip leading zeros is
str = str.replaceAll("^0+", "");
This regex will match 0
character in quantity of one and more
at the string beginning.
There is not reason to worry about replaceAll
method, as regex has ^
(begin input) special character that assure the replacement will be invoked only once.
Ultimately you can use Java build-in feature to do the same:
String str = "00000004334300343";
long number = Long.parseLong(str);
// outputs 4334300343
The leading zeros will be stripped for you automatically.
\b0+\B
will do the work. See demo \b
anchors your match to a word boundary, it matches a sequence of one or more zeros 0+
, and finishes not in a word boundary (to not eliminate the last 0
in case you have only 00...000
)
Another solution (might be more intuitive to read)
str = str.replaceFirst("^0+", "");
^
- match the beginning of a line
0+ - match the zero digit character one or more times
A exhausting list of pattern you can find here Pattern.
Accepted solution will fail if you need to get "0" from "00". This is right one:
str = str.replaceAll("0+(?!$)", "");
"^0+(?!$)" means match one or more zeros if it is not followed by end of string.
If you know input strings are all containing digits then you can do:
String s = "00000004334300343";
System.out.println(Long.valueOf(s));
// 4334300343
Code Demo
By converting to Long
it will automatically strip off all leading zeroes.