0

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.

3

3 Answers 3

2

Because of spaces in content; remove the ^ and $ to match anywhere:

([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)

Sign up to request clarification or add additional context in comments.

Comments

0

Try this one as a regex, but I am completely not sure whether it will work for you:

([^@|\s]+@[^@]+.[^@|\s]+)

5 Comments

| inside character class is a red flag - are you sure you want to exclude it from the character class?
@nhahtdh, As I told, I am not sure that it will work in all cases, it worked on me when I faced the same problem
| should not be used to say "alternation" in character class. [@\s] is already an alternation of 2 choices @ or space character class. The extra | will add the literal | to the list of alternation.
@nhahtdh, I just checked again and it worked on 'My email is [email protected]' perfectly, returning "[email protected]"
I'm not commenting about the correctness of your regex with respect to the question. I'm saying | should not be used as "alternation" in character class.
0

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-.]+$)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.