Extract email sub-strings from large document

Question:

I have a very large .txt file with hundreds of thousands of email addresses scattered throughout. They all take the format:

...<[email protected]>...

What is the best way to have Python to cycle through the entire .txt file looking for a all instances of a certain @domain string, and then grab the entirety of the address within the <…>’s, and add it to a list? The trouble I have is with the variable length of different addresses.

Asked By: user1893148

||

Answers:

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  [email protected]"
>>> match = re.search(r'[w.+-]+@[w-]+.[w.-]+', line)
>>> match.group(0)
'[email protected]'

If you have several email addresses use findall:

>>> line = "should we use regex more often? let me know at  [email protected] or [email protected]"
>>> match = re.findall(r'[w.+-]+@[w-]+.[w.-]+', line)
>>> match
['[email protected]', '[email protected]']

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 [email protected]. my regex returns [email protected]. (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 [email protected] as well.

Edit III: Added further improvements as discussed in the comments: "In addition to allowing + in the beginning of the address, this also ensures that there is at least one period in the domain. It allows multiple segments of domain like abc.co.uk as well, and does NOT match bad@ss :). Finally, you don’t actually need to escape periods within a character class, so it doesn’t do that."


Update 2023
Seems stackabuse has compiled a post based on the popular SO answer mentioned above.

import re

regex = re.compile(r"([-!#-'*+/-9=?A-Z^-~]+(.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ t]|(\[t -~]))+")@([-!#-'*+/-9=?A-Z^-~]+(.[-!#-'*+/-9=?A-Z^-~]+)*|[[t -Z^-~]*])")

def isValid(email):
    if re.fullmatch(regex, email):
        print("Valid email")
    else:
        print("Invalid email")

isValid("[email protected]")
isValid("[email protected]")
isValid("[email protected]")
isValid("[email protected]")
Answered By: 0x90

If you’re looking for a specific domain:

>>> import re
>>> text = "this is an email [email protected], it will be matched, [email protected] will not, and [email protected] will"
>>> match = re.findall(r'[w-._+%][email protected]',text) # replace test.com with the domain you're looking for, adding a backslash before periods
>>> match
['[email protected]', '[email protected]']
Answered By: tehsockz

You can also use the following to find all the email addresses in a text and print them in an array or each email on a separate line.

import re
line = "why people don't know what regex are? let me know [email protected], [email protected] " 
       "[email protected],[email protected]"
match = re.findall(r'[w.-]+@[w.-]+', line)
for i in match:
    print(i)

If you want to add it to a list just print the "match"

# this will print the list
    print(match)
Answered By: Stryker

Here’s another approach for this specific problem, with a regex from emailregex.com:

text = "blabla <[email protected]>><[email protected]> <huhu@fake> bla bla <[email protected]>"

# 1. find all potential email addresses (note: < inside <> is a problem)
matches = re.findall('<S+?>', text)  # ['<[email protected]>', '<[email protected]>', '<huhu@fake>', '<[email protected]>']

# 2. apply email regex pattern to string inside <>
emails = [ x[1:-1] for x in matches if re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$)", x[1:-1]) ]
print emails   # ['[email protected]', '[email protected]', '[email protected]']
Answered By: nischi
import re
rgx = r'(?:.?)([w-_+#~!$&'.]+(?<!.)(@|[ ]?(?[ ]?(at|AT)[ ]?)?[ ]?)(?<!.)[w]+[w-.]*.[a-zA-Z-]{2,3})(?:[^w])'
matches = re.findall(rgx, text)
get_first_group = lambda y: list(map(lambda x: x[0], y))
emails = get_first_group(matches)

Forgive me lord for having a go at this infamous regex. The regex works for a decent portion of email addresses shown below. I mostly used this as my basis for the valid chars in an email address.

enter image description here

Feel free to play around with it here

I also made a variation where the regex captures emails like name at example.com

(?:.?)([w-_+#~!$&'.]+(?<!.)(@|[ ](?[ ]?(at|AT)[ ]?)?[ ])(?<!.)[w]+[w-.]*.[a-zA-Z-]{2,3})(?:[^w])
Answered By: david_adler
import re 
txt = 'hello from [email protected] to [email protected] about the meeting @2PM'
email  =re.findall('S+@S+',s)
print(email)

Printed output:

['[email protected]', '[email protected]']
Answered By: Ayoub EL MAJJODI
import re
with open("file_name",'r') as f:
    s = f.read()
    result = re.findall(r'S+@S+',s)
    for r in result:
        print(r)
Answered By: Laksh Jadhwani
import re
mess = '''[email protected] [email protected]
            abc@gmail'''
email = re.compile(r'([w.-][email protected])')
result= email.findall(mess)

if(result != None):
    print(result)

The above code will help to you and bring the Gmail, email only after calling it.

Answered By: Muneer Ahmad
import re

reg_pat = r'S+@S+.S+'

test_text = '[email protected]    [email protected]   uiufubvcbuw bvkw  ko@com    m@urice'   

emails = re.findall(reg_pat ,test_text,re.IGNORECASE)
print(emails)

Output:

['[email protected]', '[email protected]']
Answered By: Palash Jhamb

You can use b at the end to get the correct email to define ending of the email.

The regex

[w.-]+@[w-.]+b
Answered By: Rishang

Example : string if mail id has (a-z all lower and _ or any no.0-9), then below will be regex:

>>> str1 = "[email protected]"
>>> regex1 = "^[a-z0-9]+[._]?[a-z0-9]+[@]w+[.]w{2,3}$"
>>> re_com = re.compile(regex1)
>>> re_match = re_com.search(str1)
>>> re_match
<_sre.SRE_Match object at 0x1063c9ac0>
>>> re_match.group(0)
'[email protected]'
Answered By: Aashutosh jha
content = ' abcdabcd [email protected]  afgh [email protected]  qwertyuiop [email protected]'

match_objects = re.findall(r'w+@w+[.w+]+', content)
Answered By: Sandeep Maurya
#    b[w|.]+   ---> means begins with any english and number character or dot.

import re

marks = '''

!()[]{};?#$%:'",/^&é*

'''

text = 'Hello from [email protected] to [email protected], datascience@@gmail.com and machinelearning@@yahoo..com wrong email address: [email protected]'
# list of sequences of characters:
text_pieces = text.split()
pattern = r'b[a-zA-Z]{1}[w|.]*@[w|.]+.[a-zA-Z]{2,3}$'
for p in text_pieces:
  for x in marks:
    p = p.replace(x, "") 
  if len(re.findall(pattern, p)) > 0:
    print(re.findall(pattern, p))
Answered By: Farzad Amirjavid

One other way is to divide it into 3 different groups and capture the group(0). See below:

emails=[]
for line in email: # email is the text file where some emails exist. 
    e=re.search(r'([.wd-]+)(@)([.wd-]+)',line) # 3 different groups are composed. 
    if e:
        emails.append(e.group(0))

print(emails)
Answered By: Baris Ozensel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.