使用正则表达式提取电子邮件和名称 [英] Extract email and name with regex
问题描述
从这样的字符串中提取姓名和电子邮件的正则表达式是什么?
What would be the regular expressions to extract the name and email from strings like these?
johndoe@example.com
John <johndoe@example.com>
John Doe <johndoe@example.com>
"John Doe" <johndoe@example.com>
可以假定该电子邮件有效.该名称将由电子邮件分隔一个空格,并且可能会用引号引起来.
It can be assumed that the email is valid. The name will be separated by the email by a single space, and might be quoted.
预期结果是:
johndoe@example.com
Name: nil
Email: johndoe@example.com
John <johndoe@example.com>
Name: John
Email: johndoe@example.com
John Doe <johndoe@example.com>
Name: John Doe
Email: johndoe@example.com
"John Doe" <johndoe@example.com>
Name: John Doe
Email: johndoe@example.com
这是我到目前为止的进展:
This is my progress so far:
(("?(.*)"?)\s)?(<?(.*@.*)>?)
(可以在此处进行测试: http://regexr.com/?337i5 )
(which can be tested here: http://regexr.com/?337i5)
推荐答案
以下正则表达式似乎适用于所有输入,并且仅使用两个捕获组:
The following regex appears to work on all inputs and uses only two capturing groups:
(?:"?([^"]*)"?\s)?(?:<?(.+@[^>]+)>?)
感谢@RohitJain和@burning_LEGION分别介绍了非捕获组和字符排除的概念.
Thanks to @RohitJain and @burning_LEGION for introducing the idea of non-capturing groups and character exclusion respectively.
这篇关于使用正则表达式提取电子邮件和名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!