-2

I am trying to strip all leading zeroes but retain one from strings . for eg:

if string is 000111 return 0111
if string is 00111 return 0111
if string is 0111 return 0111
if string is 1111 return 1111

the regex is working good, but if my string is say "3001" then the regex is returning 301 instead of 3001.

scala> "00111".replaceAll("[0]*(0\\d+)", "$1")
res9: String = 0111

scala> "0111".replaceAll("[0]*(0\\d+)", "$1")
res10: String = 0111

scala> "3001".replaceAll("[0]*(0\\d+)", "$1")
res11: String = 301

What am I missing here???

darkmatter
  • 125
  • 1
  • 2
  • 10
  • 1
    The proposed duplicate uses the same Java regex engine, and it contains multiple answers with the `^`-anchor, so it should solve the problem. – Andrey Tyukin Jan 13 '19 at 10:34

2 Answers2

3

You could do this without using a capturing group by matching 1+ times a zero from the start of the string ^0+ and replace with 0.

If it must be followed by a digit you could use ^0+(?=\d)

"00111".replaceAll("^0+", "0") // 0111
"0111".replaceAll("^0+", "0") // 0111
"3001".replaceAll("^0+", "0") // 3001
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

You are missing the start-of-line anchor ^. And [0] is same as 0:

"00111".replaceAll("^0*(0\\d+)", "$1")
> 0111
"3001".replaceAll("^0*(0\\d+)", "$1")
> 3001
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93