Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match 10 or 12 digits only

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}$"
like image 741
KbiR Avatar asked May 09 '17 06:05

KbiR


People also ask

How do I match a range of numbers in regex?

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.

Which regex matches one or more digits?

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.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How does regex Match 5 digits?

match(/(\d{5})/g);


2 Answers

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

like image 60
Douwe de Haan Avatar answered Sep 19 '22 14:09

Douwe de Haan


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}$'
like image 22
W.Mann Avatar answered Sep 16 '22 14:09

W.Mann