0

I would like to use a regular expression to match a number with a defined length and leading zeros. For example with number length of 6:

"000123" //Match
"002535" //Match
"2654" //No match
"000021" //Match

Which regular expression can I use for this?

3 Answers3

8

Surely this is the simplest:

^0\d{5}$

Although not stated in the question as a requirement, to exclude an all-zero input, use a negative look ahead for that case:

^(?!0+$)0\d{5}$
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • +1, duh... Much better than mine (deleting it). But needs anchors. – zx81 Jul 23 '14 at 21:30
  • @zx81 I've used your idea to post a working regex wich rejects `000000` ;) – AlexR Jul 23 '14 at 21:32
  • @Bohemian very clever ;) I usually refrain from lookahead and lookbehind in java because their implementations are / were seriously bugged. (+1) – AlexR Jul 24 '14 at 08:26
3

If 000000 is a valid match, use the answer by @Bohemian♦.

If 000000 is not allowed, used this variation on his answer (and please accept his answer not mine):

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

See the matches in the demo.

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • The lookahead (?=0+[1-9]) asserts that what follows is any number of zeroes followed by one char that is a 1 or a 9
  • 0 matches one zeroes
  • \d{5} matches five digits
  • The $ anchor asserts that we are at the end of the string

Reference

Community
  • 1
  • 1
zx81
  • 41,100
  • 9
  • 89
  • 105
1

Actually if you allow any combination of exactly six (6) digits from 0 to 9, the regex would be

^\d{6}$

If you only allow five (5) arbitrary digits and at least one leading zero, use

^0\d{5}$

instead.

If you want to disallow 000000 you need to do lookahead:

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

And finally, if you want to disallow 000000 and force a leading 0, use

^(?=\d{6}$)0\d*[1-9]\d*
AlexR
  • 2,412
  • 16
  • 26
  • There is a much easier way to disallow `000000`. Simply use it as the first pattern of an or, then capture the other pattern. `^000000$|^(0\d{5})$` – Adam Smith Jul 24 '14 at 00:06