我目前使用下面的代码:如何检查字符串是否为电子邮件?
regexp = re.compile(r'[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}', re.IGNORECASE)
email = regexp.findall(stext)
if email:
email = email[0]
但即使stext
包含一些其他的文本以及除了电子邮件,将工作(为前,some text [email protected] some other text
)。当我想检查是否stext
包含[email protected]
只有(好的,可能与前导或/和尾随空格,没有其他字符)。
PS。我也认为可能我应该使用mail.is_email_valid
而不是正则表达式,它will allow我支持像.museam
这样的长域或者像.рф
这样的本地域。
可以使用'^'和'$'特殊字符分别匹配字符串的开头和结尾。就像'r'^ [A-Z0-9 ._%+ - ] + @ [A-Z0-9 .-] + \。[A-Z] {2,4} $''会让你开始。 – jedwards 2013-03-22 19:07:18
http://docs.python.org/2/library/re.html#search-vs-match – 2013-03-22 19:54:25