Python Regular Expressions, find Email Domain in Address

Here's something I think might help

import re
s = 'My name is Conrad, and [email protected] is my email.'
domain = re.search("@[\w.]+", s)
print domain.group()

outputs

@gmail.com

How the regex works:

@ - scan till you see this character

[\w.] a set of characters to potentially match, so \w is all alphanumeric characters, and the trailing period . adds to that set of characters.

+ one or more of the previous set.

Because this regex is matching the period character and every alphanumeric after an @, it'll match email domains even in the middle of sentences.


Ok, so why not use split? (or partition )

"@"+'[email protected]'.split("@")[-1]

Or you can use other string methods like find

>>> s="[email protected]"
>>> s[ s.find("@") : ]
'@gmail.com'
>>>

and if you are going to extract out email addresses from some other text

f=open("file")
for line in f:
    words= line.split()
    if "@" in words:
       print "@"+words.split("@")[-1]
f.close()

Using regular expressions:

>>> re.search('@.*', test_string).group()
'@gmail.com'

A different way:

>>> '@' + test_string.split('@')[1]
'@gmail.com'