arizals
arizals

Reputation: 47

Email Validation using Python Regular Expression

I have 9 email patterns. I expect:

and

Then, I have made script of regex like:

regex = r"(^[a-zA-Z_]+[\.]?[a-z0-9]+)@([\w.]+\.[\w.]+)$"

But, email [email protected] is still valid.

How to make the right pattern regex so that email become not valid, and all of email patterns can fit to my expectation?

Upvotes: 1

Views: 817

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

For the example data you could either match an optional part with underscores where a dot followed by a digit is allowed before the @

Or you match a part that with a dot and a char a-z before the @

 ^[a-zA-Z]+(?:(?:_[a-zA-Z0-9]+)+\.[A-Za-z0-9]+|\.[a-zA-Z][a-zA-Z0-9]*)?@(?:[a-zA-Z0-9]+\.)*[a-zA-Z0-9]{2,}$

Explanation

  • ^ Start of string
  • [a-zA-Z]+ Match 1+ times a char a-z
  • (?: Non capture group
    • (?:_[a-zA-Z0-9]+)+ Repeat 1+ times an underscore followed by a char a-z or digit 0-9
    • \.[A-Za-z0-9]+ Match a dot and 1+ chars a-z or digit 0-9
    • | Or
    • \.[a-zA-Z][a-zA-Z0-9]* Match a a dot and a single char a-z and 0+ chars a-z or digits
  • )? Close group and make it optional
  • @ Match literally
  • (?:[a-zA-Z0-9]+\.)* Repeat 0+ times a-z0-9 followed by a dot
  • [a-zA-Z0-9]{2,} Match a-z0-9 2 or more times
  • $ End of string

Regex demo

Upvotes: 1

Ωmega
Ωmega

Reputation: 43663

Use the following regex pattern with gmi flags:

^[a-z]+(?:(?:\.[a-z]+)+\d*|(?:_[a-z]+)+(?:\.\d+)?)?@(?!.*\.\.)[^\W_][a-z\d.]+[a-z\d]{2}$

https://regex101.com/r/xoVprE/4

Upvotes: 0

Related Questions