Reputation: 25328
Here are two possible email string scenarios:
email = "Joe Schmoe <[email protected]>"
email = "[email protected]"
I always only want [email protected]
.
So what would the regex or method be that would account for both scenarios?
Upvotes: 0
Views: 370
Reputation: 31280
If those are the only two formats, don't use a regex. Just use simple string parsing. IF you find a "<>
" pair, then pull the email address out from between them, and if you don't find those characters, treat the whole string as the email address.
Regexes are great when you need them, but if you have very simple patterns, then the overhead of loading in and parsing down the regex and processing with it will be much higher than simple string manipulation. Not loading in extra libraries other than what is very core in a language will almost always be faster than going a different route.
Upvotes: 2
Reputation: 4032
If you know your email is always going to be in the < >
then you can do a sub string with those as the starting and ending indexes.
Upvotes: 2
Reputation: 31726
This passes your examples:
def find_email(string)
string[/<([^>]*)>$/, 1] || string
end
find_email "Joe Schmoe <[email protected]>" # => "[email protected]"
find_email "[email protected]" # => "[email protected]"
Upvotes: 3
Reputation: 26979
If you are willing to load an extra library, this has already been solved in the TMail gem: http://lindsaar.net/2008/4/13/tip-5-cleaning-up-an-verifying-an-email-address-with-ruby-on-rails
TMail::Address.parse('Mikel A. <[email protected]>').spec
=> "[email protected]"
Upvotes: 0