简体   繁体   中英

Parse small string for name and email?

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 do 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM