Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

language agnostic - Extract email and name with regex

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.

The expected results are:

[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)?(<?(.*@.*)>?)

(which can be tested here: http://regexr.com/?337i5)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following regex appears to work on all inputs and uses only two capturing groups:

(?:"?([^"]*)"?s)?(?:<?(.+@[^>]+)>?)

http://regex101.com/r/dR8hL3

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...