Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 825
hpique Avatar asked Dec 23 '12 12:12

hpique


People also ask

How do I extract an email address from a regular expression?

In the example, we created a function with regex /([a-zA-Z0-9. _-]+@[a-zA-Z0-9. _-]+\. [a-zA-Z0-9_-]+)/ to extract email ids (address) from the long text.

How do I extract email addresses from a string in Python?

To extract emails form text, we can take of regular expression. In the below example we take help of the regular expression package to define the pattern of an email ID and then use the findall() function to retrieve those text which match this pattern.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.


1 Answers

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.

like image 190
hpique Avatar answered Oct 04 '22 23:10

hpique