Reputation: 19
I am trying to get all email address from a text file using regular expression and Python but it always returns NoneType while it suppose to return the email. For example:
content = 'My email is [email protected]'
#Compare with suitable regex
emailRegex = re.compile(r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)')
mo = emailRegex.search(content)
print(mo.group())
I suspect the problem lies in the regex but could not figure out why.
Upvotes: 0
Views: 196
Reputation: 5263
Because of spaces in content
; remove the ^
and $
to match anywhere:
([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)
Upvotes: 2
Reputation: 282
Your regular expression doesn't match the pattern.
I normally call the regex search like this:
mo = re.search(regex, searchstring)
So in your case I would try
content = 'My email is [email protected]'
#Compare with suitable regex
emailRegex = re.compile(r'gmail')
mo = re.search(emailRegex, content)
print(mo.group())`
You can test your regex here: https://regex101.com/ This will work:
([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)
Upvotes: 0
Reputation: 3081
Try this one as a regex, but I am completely not sure whether it will work for you:
([^@|\s]+@[^@]+.[^@|\s]+)
Upvotes: 0