1

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?

2
  • Maybe ^(?![a-zA-Z]+\.\d+@)[a-zA-Z_]+(?:\.[a-z0-9]+)?@[\w.]+\.\w+$ will do, see demo. Commented Apr 9, 2020 at 14:22
  • Perhaps with an optional part matching the underscore or start the match with a-z before the dot ^[a-zA-Z]+(?:(?:(?:_[a-zA-Z0-9]+)+\.[A-Za-z0-9]+)|\.[a-zA-Z][a-zA-Z0-9]*)?@\w+(?:\.\w+)+ regex101.com/r/Q3TxQc/1 Commented Apr 9, 2020 at 17:00

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.