'regex to strip leading zeros treated as string

I have numbers like this that need leading zero's removed.

Here is what I need:

00000004334300343 -> 4334300343

0003030435243 -> 3030435243

I can't figure this out as I'm new to regular expressions. This does not work:

(^0)


Solution 1:[1]

Accepted solution will fail if you need to get "0" from "00". This is the right one:

str = str.replaceAll("^0+(?!$)", "");

^0+(?!$) means match one or more zeros if it is not followed by end of string.

Thank you to the commenter - I have updated the formula to match the description from the author.

Solution 2:[2]

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.

Solution 3:[3]

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.

Solution 4:[4]

\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)

Solution 5:[5]

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.

Solution 6:[6]

I know this is an old question, but I think the best way to do this is actually

str = str.replaceAll("(^0+)?(\d+)", "$2")

The reason I suggest this is because it splits the string into two groups. The second group is at least one digit. The first group matches 1 or more zeros at the start of the line. However, the first group is optional, meaning that if there are no leading zeros, you just get all of the digits. And, if str is only a zero, you get exactly one zero (because the second group must match at least one digit).

So if it's any number of 0s, you get back exactly one zero. If it starts with any number of 0s followed by any other digit, you get no leading zeros. If it starts with any other digit, you get back exactly what you had in the first place.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tripleee
Solution 2 anubhava
Solution 3
Solution 4 Luis Colorado
Solution 5
Solution 6 Kruglord