How to count only digits length regex

Viewed 217

Russian phone number has 11 digits, but i couldn't use a{11}, because phone number can contain brackets and dashes
My regex: ^([\+]?\d){1,2}([\(\-]*[0-9]{3}[\)\-]*)([0-9\-]{7,9})$
Number can have from 1 to 2 characters as a country code
then 3 digits with brackets or not as phone operator code
then from 7-9 digits with dashes or not

For example:

+7(994)849-45-16
+7(994)849-4516
+7(994)84945-16
+7994849-45-16

Question is, how i can count lenght of only digits in regex

1 Answers

You can use

^(?!(?:\D*\d){12})(\+?\d{1,2})([(-]*[0-9]{3}[)-]*)([0-9](?:-?[0-9]){6,8})$

See the regex demo

Details

  • ^ - start of string
  • (?!(?:\D*\d){12}) - no more than 11 digits are allowed in the string
  • (\+?\d{1,2}) - Group 1: an optional + and then 1 or 2 digits
  • ([(-]*[0-9]{3}[)-]*) - Group 2: zero or more ( or - chars, three digits, and then again zero or more ) or - chars
  • ([0-9](?:-?[0-9]){6,8}) - Group 3: a digit and then 6 to 8 occurrences of an optional - and a digit
  • $ - end of string.
Related