I tried to write a regex to match a 10 or 12 digits number combination. like:
1234567890 - True
123456789012 - True
12345678901 - False
123456- False
1234567890123- False
Only match either 10 or 12 digits. I tried this:
"^[0-9]{10}|[0-9]{12}$"
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.
Occurrence Indicators (or Repetition Operators): +: 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.
$ means "Match the end of the string" (the position after the last character in the string).
match(/(\d{5})/g);
You're close!
This is the regex you're looking for: ^(\d{10}|\d{12})$
. It checks for digits (with \d
). The rest is more or less your code, with the exception of the parenthesis. It captures each group. You could loose those, if you want to work without it!
See it in action here
Your regex either matches 10 digits at the beginning of a string (with any characters more allowed after that), or 12 digits at the end of the string. One option to make your regex work is:
"^[0-9]{10}$|^[0-9]{12}$"
although it's better to use raw strings for the pattern:
r'^[0-9]{10}$|^[0-9]{12}$'
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