user1930999
user1930999

Reputation: 23

Java Regex to strip all leading zeros in a delimited String

I have the string "08,09,10,11" and I want "8,9,10,11" i.e. strip all leading zeros.

The regex

"08,09,10,11".replaceAll("^0+(?!$)", "")

is close but gives me '8,09,10,11' (i.e. the zero on the 9 is not stripped.

Anyone got a regex I can use to do what I need?

Upvotes: 2

Views: 7960

Answers (3)

rustyfinger
rustyfinger

Reputation: 342

Here the different between two approaches mention:

str.replaceAll("^0+", "")

"0001000" ----> "1000"
"0000000" ----> ""


replaceAll("^0+(?!$)", "")

"0001000" ----> "1000"
"0000000" ----> "0"

(?!$) is a so called negative lookahead looking out for the end of the string and do not remove the "0" followed by the end of the string. therefore if a leading zero is also the last character of the string it does not get removed

Upvotes: 2

pconrey
pconrey

Reputation: 6005

This will work:

str.replaceAll("^0+", "")

Upvotes: 5

Michael
Michael

Reputation: 3332

I think this will work:

str.replaceAll("(?<!\d)0+(?=\d+)", "");

And here are some tests: http://fiddle.re/rp57

Upvotes: 4

Related Questions