3

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

Email: Joe Schmo <joeschmo@abc123.com>

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 <joeschmo@abc123.com>"

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?

sjsc
  • 4,552
  • 10
  • 39
  • 55
  • 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. – Ignacio Vazquez-Abrams Feb 11 '10 at 22:29
  • Thank you Ignacio for the tip! – sjsc Feb 11 '10 at 22:34
  • Using parallel assignment should eliminate the need for a temporary variable altogether (cast match result to an array first). – bta Feb 11 '10 at 22:41
  • There are several questions asking about regular expressions for emails. http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses 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 http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Andrew Grimm Feb 12 '10 at 02:07

1 Answers1

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

Then grab what you want out of the capturing groups.

Anon.
  • 58,739
  • 8
  • 81
  • 86
  • 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). – bta Feb 11 '10 at 22:39
  • Better yet: `name, domain, email = (/Email: (.+) <(.+?)@(.+)>/).match(the_email_line).to_a[1..3]` – bta Feb 11 '10 at 22:50