使用正则表达式提取电子邮件和名称

使用正则表达式提取电子邮件和名称

本文介绍了使用正则表达式提取电子邮件和名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从这样的字符串中提取姓名和电子邮件的正则表达式是什么?

What would be the regular expressions to extract the name and email from strings like these?

[email protected]
John <[email protected]>
John Doe <[email protected]>
"John Doe" <[email protected]>

可以假定该电子邮件有效.该名称将由电子邮件分隔一个空格,并且可能会用引号引起来.

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.

预期结果是:

[email protected]
Name: nil
Email: [email protected]

John <[email protected]>
Name: John
Email: [email protected]

John Doe <[email protected]>
Name: John Doe
Email: [email protected]

"John Doe" <[email protected]>
Name: John Doe
Email: [email protected]

这是我到目前为止的进展:

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)?(?:<?(.+@[^>]+)>?)

http://regex101.com/r/dR8hL3

感谢@RohitJain和@burning_LEGION分别介绍了非捕获组和字符排除的概念.

Thanks to @RohitJain and @burning_LEGION for introducing the idea of non-capturing groups and character exclusion respectively.

这篇关于使用正则表达式提取电子邮件和名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:19