【问题标题】:How can I get actual email address as a string from python email object如何从 python 电子邮件对象中获取实际的电子邮件地址作为字符串
【发布时间】:2014-01-11 05:53:14
【问题描述】:

我已经使用 python 的 imaplib 创建了一个电子邮件对象:

import email
email_message = email.message_from_string(raw_email)

>>> f = email_message ['From']
>>> f
'"bob smith" <bob5@xxxxx.org>'
>>> import re
>>> re.findall('\$<[^$]*>\$', f)
[]

我想获取实际的电子邮件,但上述方法不起作用。我该怎么做?

【问题讨论】:

  • “不工作”是什么意思?
  • 我上面的正则表达式产生一个空集“[]”。我正在展示我的交互式 python 代码 -Bill
  • re.findall("",f)

标签: python regex email


【解决方案1】:

我不知道所有美元符号的用途,但它们不是必需的。你想要得到的东西可以方便地放在尖括号内。因此,您需要做的就是捕获其中包含的内容。

这可以通过re.search来完成:

>>> from re import search
>>> f = '"bob smith" <bob5@xxxxx.org>'
>>> search('<(.*?)>$', f)
<_sre.SRE_Match object at 0x0213A520>
>>> search('<(.*?)>$', f).group(1)
'bob5@xxxxx.org'
>>>

下面是正则表达式模式的细分:

<      # <
(.*?)  # Capture group for zero or more characters
>      # >
$      # End of string

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 2017-01-16
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多