You can use range quantifier {min,max}
to specify minimum of 1 digit and maximum of 6 digits as:
^[0-9]{1,6}$
Explanation:
^ : Start anchor
[0-9] : Character class to match one of the 10 digits
{1,6} : Range quantifier. Minimum 1 repetition and maximum 6.
$ : End anchor
Why did your regex not work ?
You were almost close on the regex:
^[0-9][0-9]?[0-9]?[0-9]?[0-9]?[0-9]?$
Since you had escaped the ?
by preceding it with the
, the ?
was no more acting as a regex meta-character ( for 0
or 1
repetitions) but was being treated literally.
To fix it just remove the
and you are there.
See it on rubular.
The quantifier based regex is shorter, more readable and can easily be extended to any number of digits.
Your second regex:
^[0-999999]$
is equivalent to:
^[0-9]$
which matches strings with exactly one digit. They are equivalent because a character class [aaaab]
is same as [ab]
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…