Skip to content Skip to sidebar Skip to footer

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 Onl

Solution 1:

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

Solution 2:

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}$'

Solution 3:

there is another approach, you can do it like this way.

^\d{10}(\d{2})?$

Post a Comment for "Regex To Match 10 Or 12 Digits Only"