4

Here is a weird regular expression for emails .

We can have various kind of email addresses

[email protected]

[email protected]

[email protected]

[email protected]

The following regular expression can find any of the mails above

email2="[email protected]"
email1="[email protected]'"
email="[email protected]"
email3="[email protected]"
email4="[email protected]"
email5="[email protected]"
email6="[email protected]"





re.search('\w+[.|\w]\w+@\w+[.]\w+[.|\w+]\w+',email)

x=re.search('\w+[.|\w]\w+@\w+[.]\w+[.|\w+]\w+',email2)
x.group()
[email protected]'
x=re.search('\w+[.|\w]\w+@\w+[.]\w+[.|\w+]\w+',email1)
x.group()
[email protected]'
x=re.search('\w+[.|\w]\w+@\w+[.]\w+[.|\w+]\w+',email)
x.group()
'[email protected]'

This seems too complicated right...

I generalized it a bit....

x=re.search('(\w+[.|\w])*@(\w+[.])*\w+',email4)
x.group()
'[email protected]'

The above regular expression now can detect any type of combination...

Now if you want only email address ending with '.in' or '.com' then you can add a variation...

x=re.search('(\w+[.|\w])*@(\w+[.])*(com$|in$)',email)

You can try out this on various combinations.... If the expression does not fit anywhere , do tell me .

Some assumptions I have used : email address(username) wont contain special characters , only words or numbers.

Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63
  • possible duplicate of [Python check for valid email address?](http://stackoverflow.com/questions/8022530/python-check-for-valid-email-address) – phihag Jan 15 '12 at 10:24
  • 1
    @phihag I do not think it is a dupe, I think it's not even a question, actually. – amit Jan 15 '12 at 10:25
  • 1: What's the question? 2: Using regular expressions to validate email addresses is a very very deep rabbit hole, see http://www.regular-expressions.info/email.html – Simon Righarts Jan 15 '12 at 10:27
  • possible duplicate of [What is the best regular expression for validating email addresses?](http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses) – jcollado Jan 15 '12 at 10:41
  • Sorry for the above post...I meant to share what I did...Its not a question...Its just info sharing... – Arindam Roychowdhury Dec 19 '16 at 11:20

1 Answers1

3

As answered on stackoverflow, the correct regexp for emails is way more complicated than that.

Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
  • I do not know if this is a duplicate........i worked on it .....thought it was worth sharing........Its not a question ......Just something i thought worth sharing....... – Arindam Roychowdhury Jan 16 '12 at 09:37
  • 1
    regardless of what the folks @ stack overflow care to disregard as tripe, Arindam's post was EXTREEEEEEMELY MF helpful to me, personally. Plus it helps their SEO. Just sayin... – Rob Truxal Mar 04 '17 at 04:02