Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a 9 or 14 digits long number with regex?

Tags:

regex

I need to check by Regex expression if 9 or 14 digits are typed.

The expression \d{9}|\d{14} seems to be not working properly, what's wrong ?

like image 428
Tony Avatar asked Dec 28 '09 19:12

Tony


People also ask

How do I match a range of numbers in regex?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).

Which regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

How do I match a pattern in regex?

Regular expressions, called regexes for short, are descriptions for a pattern of text. For example, a \d in a regex stands for a digit character — that is, any single numeral 0 to 9. Following regex is used in Python to match a string of three numbers, a hyphen, three more numbers, another hyphen, and four numbers.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.


2 Answers

This regex should work.

^(\d{9}|\d{14})$

Could you post the piece of code you're using and tell us what language are you using? If you're using regex chances are that you have a string, and I'm sure your language has something to count string length.

EDIT:
as Rubens Farias pointed out in comments maybe ^...$ is needed because your regex would match any number with more than 9 digit as that number has a substring with a 9 digit long number.

Anyway check if you can do it with your language's string's methods/functions

like image 186
Andrea Ambu Avatar answered Oct 06 '22 00:10

Andrea Ambu


You can use:

^(?:\d{9}|\d{14})$

Explanation:

^       - Start anchor
(?:     - Start of non-capturing group      
 \d{9}  - 9 digits
 |      - alternation
 \d{14} - 14 digits
)       - close of the group.
$       - End anchor

alternatively you can do:

^\d{9}(?:\d{5})?$

which matches 9 digits followed by optional 5 digits.

like image 43
codaddict Avatar answered Oct 06 '22 00:10

codaddict