Skip to content Skip to sidebar Skip to footer

Python Regexp To Match E-mail Against Domain Names

I'm looking for the 'perfect' regexp's to validate if an e-mail belongs to a domain name (including sub-domains), for example: www.domain.com : some1@domain.com sub.domain.com : so

Solution 1:

Taken from django:

email_re = re.compile(
    r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"# dot-atomr'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"'# quoted-stringr')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE)  # domain

Solution 2:

You don't need a regex:

>>>defmatch_domain(domain, email):...return email.endswith(domain.lstrip('www.'))...>>>match_domain('www.domain.com', 'some1@domain.com')
True
>>>match_domain('www.domain.com', 'some1@www.domain.com')
True
>>>match_domain('sub.domain.com', 'some1@sub.domain.com')
True
>>>match_domain('sub.domain2.com', 'some1@sub.domain.com')
False
>>>match_domain('domain2.com', 'some1@domain.com')
False

Post a Comment for "Python Regexp To Match E-mail Against Domain Names"