This code extracts the email addresses in a string. Use it while reading line by line
>>> import re
>>> line = "should we use regex more often? let me know at 321dsasdsa@dasdsa.com.lol"
>>> match = re.search(r'[\w\.-]+@[\w\.-]+', line)
>>> match.group(0)
'321dsasdsa@dasdsa.com.lol'
If you have several email addresses use findall
:
>>> line = "should we use regex more often? let me know at 321dsasdsa@dasdsa.com.lol"
>>> match = re.findall(r'[\w\.-]+@[\w\.-]+', line)
>>> match
['321dsasdsa@dasdsa.com.lol', 'dadaads@dsdds.com']
The regex above probably finds the most common non-fake email address. If you want to be completely aligned with the RFC 5322 you should check which email addresses follow the specification. Check this out to avoid any bugs in finding email addresses correctly.
Edit: as suggested in a comment by @kostek:
In the string Contact us at support@example.com.
my regex returns support@example.com. (with dot at the end). To avoid this, use [\w\.,]+@[\w\.,]+\.\w+)
Edit II: another wonderful improvement was mentioned in the comments: [\w\.-]+@[\w\.-]+\.\w+
which will capture example@do-main.com as well.