Regex in Python Validate E-mail

Asked

Viewed 734 times

0

Good morning!

valid = re.search(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9]+\.[a-zA-Z\.a-zA-Z]{1,3}$', email)

I have this regular expression, and there are some rules to return the correct emails, are 8 tests, and being able to pass in 7 of them, but gives me an error in 1 test, he expects to return @yahoo.com.br but only passes the email: @yahoo.com

I’ve tried a few changes but it hasn’t solved much because it passes that test and fails the others. The maximum length of the extension is 1.2 and 3 characters.

Thank you!

1 answer

0


Understanding the expression you wrote:

^[a-zA-Z0-9._-]+@[a-zA-Z0-9]+\.[a-zA-Z\.a-zA-Z]{1,3}$
 |_____________| |__________|  |____________________| 
        |             |                  |
        |             |                  +-> (3) Buscará o resto do e-mail
        |             |
        |             +-> (2) Buscará o conteúdo após o @ até encontrar o primeiro .
        |
        +-> (1) Buscará o conteúdo antes do @

To the email [email protected] we would have:

  1. The first part would take fulano;
  2. The second part would take yahoo;
  3. The third part should catch com.br;

The problem is in the third part, where you should take the value com.br, but you limited the number of characters between 1 and 3:

[a-zA-Z\.a-zA-Z]{1,3}

That explains why it works for yahoo.com, for com has only 3 letters, but for yahoo.com.br not because com.br has 6 letters, failing regular expression.

You really need to limit the number of characters in the last part?

  • Hi Anderson, thanks for the answer! So in case I need to limit the end up to 3 digits, would you be able to do this for two extensions? for example limit an email (.com.br) and (.com) also to up to 3 digits?

  • 1

    @Carol I suggest you see the duplicate question, this answer has a suggestion of what to put in regex after the @ to accept .com.br. And it also has some extra considerations, plus links to other related questions (and other regex suggestions as well)

  • thanks to all, at the end the expression was like this (r' [a-za-Z0-9. _-]+@([a-Z0-9]+)(. [a-z]{2,3})+$' and it worked

Browser other questions tagged

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