0

A friend of mine had this as a task for university. He needed a Regex to check if a 9 digit long number with leading 0+ has no more 0s after another digit.

Examples:

000001111 - good
000000010 - bad
000000000 - good
001215341 - good
165160000 - bad
0165168546 - bad

After some time we both came up with ^\b([0]+[1-9]*)\b$. However this also allows the latest example/ does not check for the correct length. He ended up checking the length with an if-statement beforehand, but I just can't find my peace because of it.

Is there an more elegant way? One Regex to do the above, but also check the length?

Kili
  • 27
  • 5
  • More elegant, and regex? The if statement is far and away the better real solution IMO. Academically, it might not fit the requirements, but that would be a different issue. – Austin T French Dec 07 '20 at 18:00

1 Answers1

1

You may use this regex with a lookahead condition:

^(?=\d{9}$)0*[1-9]*$

RegEx Demo

  • ^: Start
  • (?=\d{9}$): Lookahead condition to check for exact 9 digits
  • 0*: Match 0 or more 0
  • [1-9]*: Match 0 or more [1-9] digits
  • $: End
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Thank you. Also for the explanation, that helps a lot. I did not know about lookaheads. 0+ though for leading 0s :) – Kili Dec 07 '20 at 18:00