3

I'm trying to extract information from an email address like so in ruby:

Email: Joe Schmo <[email protected]> 

to get these three variables:

name = ? email = ? domain = ? 

I've tried searching everywhere but can't seem to find how to do it correctly. Here's what I have so far:

the_email_line = "Email: Joe Schmo <[email protected]>" name = (/^Email\: (.+) <(.+)>@[A-Z0-9.-]+\.(.+)/).match(the_email_line)[1] email = (/^Email\: (.+) <(.+)>@[A-Z0-9.-]+\.(.+)/).match(the_email_line)[2] domain = (/^Email\: (.+) <(.+)>@[A-Z0-9.-]+\.(.+)/).match(the_email_line)[3] 

Any idea on how to get those three variables correctly?

4
  • 1
    Leaving aside the fact that the regex for the email address is incomplete, you should be assigning the result of .match() to a temporary variable and indexing that. Commented Feb 11, 2010 at 22:29
  • Thank you Ignacio for the tip! Commented Feb 11, 2010 at 22:34
  • Using parallel assignment should eliminate the need for a temporary variable altogether (cast match result to an array first). Commented Feb 11, 2010 at 22:41
  • There are several questions asking about regular expressions for emails. stackoverflow.com/questions/201323/… is one of them. They aren't all ruby-related, but at least some of them use a similar regexp syntax. If you're interested in regular expression questions, you may want to check out stackoverflow.com/questions/1732348/… Commented Feb 12, 2010 at 2:07

1 Answer 1

5
/Email: (.+) <(.+?)@(.+)>/ 

Then grab what you want out of the capturing groups.

Sign up to request clarification or add additional context in comments.

2 Comments

In particular, try dummy, name, domain, email = (/Email: (.+) <(.+?)@(.+)>/).match(the_email_line).to_a. You can throw away dummy (just a copy of the matched string).
Better yet: name, domain, email = (/Email: (.+) <(.+?)@(.+)>/).match(the_email_line).to_a[1..3]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.