I need a regular expression that requires at least ONE digits and SIX maximum.
I've worked out this, but neither of them seems to work.
^[0-9][0-9]\?[0-9]\?[0-9]\?[0-9]\?[0-9]\?$ ^[0-999999]$
Any other suggestion?
n = 900000 ∴ There are 900,000 6-digit numbers in all.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.
'?' is also a quantifier. Is short for {0,1}. It means "Match zero or one of the group preceding this question mark." It can also be interpreted as the part preceding the question mark is optional. e.g.: pattern = re.compile(r'(\d{2}-)?\
In this case, [0-9]+ matches one or more digits. A regex may match a portion of the input (i.e., substring) or the entire input. In fact, it could match zero or more substrings of the input (with global modifier). This regex matches any numeric substring (of digits 0 to 9) of the input.
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With