开发者

Parse small string for name and email?

开发者 https://www.devze.com 2023-03-10 07:21 出处:网络
I have a string: John Smith <jsmith@gmail.com> I would like to get two variables: name (John Smith) and email (jsmith@gmail.com)

I have a string:

John Smith <jsmith@gmail.com>

I would like to get two variables:

name (John Smith) and email (jsmith@gmail.com)

How might I 开发者_如何学Cdo that?

Thanks for the help!


There are more forms of valid Internet Email address than you probably realize. I would suggest using somebody else's code to parse them, like email.utils.parseaddr.

For example, the following is a valid address:

"Rocky J. Squirrel" <rocky.squirrel@gmail.com>

Here, the name is Rocky J. Squirrel, not "Rocky J. Squirrel".

The following is also legal syntax and shows up regularly in mail headers (note lack of <> delimiters):

rocky.squirrel@gmail.com (Rocky J. Squirrel)

Although the part in parens is technically just a "comment", most mail clients interpret it as the user's name. (And so does Python's email.utils.parseaddr.)

To actually do the parsing (saving you reading the docs):

>>> import email.utils
>>> email.utils.parseaddr("John Smith <jsmith@gmail.com>")
('John Smith', 'jsmith@gmail.com')
0

精彩评论

暂无评论...
验证码 换一张
取 消