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 ?
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).
+: 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.
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.
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.
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
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.
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