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

Asked

Viewed 3,078 times

1

I have Pattern code: ^[1-9]{2}9?[0-9]{8}$, then 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 9 digits.

How can I do this in regex ?

Follow regex ready that I could not do: https://regex101.com/r/ZBxjSs/1

  • 2

    Just remove ,5 of your regex.

  • @Valdeirpsr, believe me, it was just removing ,5 already solves the problem.

  • @danieltakeshi, your regex lets you type more than 9 digits

  • 1

    My Regex was basically the same as its corrected, only it accepted from zero to infinite spaces. But as Valdeir said, just take the ,5... \(?\d{2}\)?\s?9?\d{4}-?\d{4}. FWIW: For a value like (12 1111-1111 is also accepted, but are typos that you can bypass with other types of programming.

1 answer

5

Following exactly the rule of the post, follow the step by step:

  • \( = Character (otherwise we would have a group
  • \d = any digit
  • {2} = repetition
  • \) = Character ), otherwise we would have a group closure
  • \s = Space
  • 9? = Character 9, the question mark serves to say that it is optional

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

Example for your doubt

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

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

Example validating the DDD better

Browser other questions tagged

You are not signed in. Login or sign up in order to post.