How to make a regex that accepts 8 or 9 digits with 2 digit DDD?

0

I have pattern code: ^[1-9]{2}9?[0-9]{8}$ , so I changed my mind to do with regex with mask and such ...

Example:

  • (11) 1111-1111 - fixo válido
  • (11) 11111-1111 - celular inválido
  • (11) 91111-1111 - celular válido
  • (11) 01111-1111 - celular inválido

Format: 2-character DDD (9th digit is optional). If you start with 9 digits, you should start with number 9.

How can I do this in regex?

Here's a regex ready that I could not do: link

    
asked by anonymous 29.01.2018 / 18:57

1 answer

4

Following exactly the rule of the post, it follows the step by step:

  • \ (= Character (otherwise we would have a group
  • \ d = Any digit
  • {2} = repetition
  • \) = Character), otherwise we would have a group close
  • \ s = Space
  • 9? = Character 9, the interrogation is to say that it is optional
  

\ (\ d {2}) \ s9? \ d {4} - \ d {4}

Example for your question

edit: There is no ddd that starts with 0, so the expression should be different:

  

\ ([1-9] \ d \) \ s9? \ d {4} - \ d {4}

Example better validating DDD

    
29.01.2018 / 21:50