0

我正在尝试从我的正则表达式匹配中返回 2 个子组:

email_add = "John@Doe.com <John@Doe.com>"
m = re.match(r"(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b) <(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b)", email_add)

但它似乎不匹配:

>>> m.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

我怀疑我可能没有正确分组,或者我使用了不正确的单词边界。我试过 \w 而不是 \b 但结果是一样的。

有人可以指出我的错误。

4

2 回答 2

2

您只匹配大写字母A-Z,因此字符序列和和导致模式不匹配任何内容。ohnoecom

添加re.I不区分大小写的标志使您的模式工作:

>>> import re
>>> email_add = "John@Doe.com <John@Doe.com>"
>>> re.match(r"(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b) <(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b)", email_add)
>>> re.match(r"(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b) <(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b)", email_add, re.I)
<_sre.SRE_Match object at 0x1030d4f10>
>>> _.groups()
('John@Doe.com', 'John@Doe.com')

或者您可以添加a-z到字符类中:

>>> re.match(r"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b) <(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b)", email_add)
<_sre.SRE_Match object at 0x1030d4f10>
>>> _.groups()
('John@Doe.com', 'John@Doe.com')
于 2013-03-01T17:12:56.427 回答
2

已指出您的正则表达式有什么问题,但您可能还需要考虑email.utils.parseaddr

>>> from email.utils import parseaddr
>>> email_add = "John@Doe.com <John@Doe.com>"
>>> parseaddr(email_add)
('', 'John@Doe.com')  # doesn't get first part, so could assume it's same as 2nd?
>>> email_add = "John Doe <John@Doe.com>"
>>> parseaddr(email_add)
('John Doe', 'John@Doe.com') # does get name and email
于 2013-03-01T17:19:13.230 回答