Reputation: 8234
Python Central published this simple script on the 29th December 2016 to check for a properly formatted email.
import re
def isValidEmail(email):
if len(email) > 7:
if re.match("^.+@([?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", email) != None:
return True
return False
if isValidEmail("[email protected]") == True:
print("This is a valid email address")
else:
print("This is not a valid email address")
While trying it, python 3 returned the following error messages:
Traceback (most recent call last):
File "~/isValidEmail.py", line 11, in <module>
if isValidEmail("[email protected]") == True:
File "~/isValidEmail.py", line 7, in isValidEmail
if re.match("^.+@([?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", email) != None:
File "/usr/lib/python3.5/re.py", line 163, in match
return _compile(pattern, flags).match(string)
File "/usr/lib/python3.5/re.py", line 293, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/lib/python3.5/sre_compile.py", line 536, in compile
p = sre_parse.parse(p, flags)
File "/usr/lib/python3.5/sre_parse.py", line 829, in parse
p = _parse_sub(source, pattern, 0)
File "/usr/lib/python3.5/sre_parse.py", line 437, in _parse_sub
itemsappend(_parse(source, state))
File "/usr/lib/python3.5/sre_parse.py", line 781, in _parse
source.tell() - start)
sre_constants.error: missing ), unterminated subpattern at position 4
How may I fix this error?
Upvotes: 2
Views: 8254
Reputation: 3372
The closing bracket )
is being included inside the square brackets because the square bracket before it isn't escaped properly.
^.+@([?)[a-zA-Z0-9-.]+.
^
v
^.+@(\[?)[a-zA-Z0-9-.]+.
Example:
In[2]: import re
...:
...:
...: def is_valid_email(email):
...: if len(email) > 7:
...: return bool(re.match(
...: "^.+@(\[?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", email))
...:
In[3]: is_valid_email("[email protected]")
Out[3]: True
Upvotes: 5