Reputation: 23
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
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
Reputation: 3332
I think this will work:
str.replaceAll("(?<!\d)0+(?=\d+)", "");
And here are some tests: http://fiddle.re/rp57
Upvotes: 4