Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

6 digits regular expression

Tags:

regex

vb.net

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?

like image 772
framara Avatar asked Jan 21 '11 11:01

framara


People also ask

How many 6 digit natural numbers are there?

n = 900000 ∴ There are 900,000 6-digit numbers in all.

Can you use regex with numbers?

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.

What is '?' In regular expression?

'?' 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}-)?\

What does the regular expression 0 9 ]+ indicate?

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.


1 Answers

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].

like image 89
codaddict Avatar answered Oct 02 '22 18:10

codaddict