Python正则表达式:反向引用匹配的正则表达式组

时间:2013-03-01 17:08:19

标签: python regex

我正在尝试从正则表达式匹配中返回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但是结果是一样的。

有人可以指出我的错误。

2 个答案:

答案 0 :(得分:2)

您只匹配大写A-Z个字母 ,因此字符序列ohnoe以及com会导致图案不匹配任何内容

添加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')

答案 1 :(得分: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