python检查有效的电子邮件

时间:2018-03-12 01:09:00

标签: python email

Python Central于2016年12月29日发布此simple script以检查格式正确的电子邮件。

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("my.email@gmail.com") == True:
    print("This is a valid email address")
else:
    print("This is not a valid email address")

尝试时,python 3返回以下错误消息:

Traceback (most recent call last):
  File "~/isValidEmail.py", line 11, in <module>
    if isValidEmail("my.email@gmail.com") == 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

我该如何解决此错误?

1 个答案:

答案 0 :(得分:5)

结束括号)包含在方括号内,因为它之前的方括号未正确转义。

^.+@([?)[a-zA-Z0-9-.]+.
     ^
     v
^.+@(\[?)[a-zA-Z0-9-.]+.

示例:

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("my.email@gmail.com")
Out[3]: True