How can I find an email address inside HTML code with Nokogiri?

nokogiri, regex, ruby, ruby-on-rails

Solution

If you're just trying to parse the email address from a string that just so happens to be HTML, Nokogiri isn't needed for this.

html_string   = "Your HTML here..."
email_address = html_string.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i)[0]

This isn't a perfect solution though, as the RFC for what constitutes a 'valid' email address is very lenient. This means most regular expressions you come across (the above one included) do not account for edge case valid addresses. For example, according to the RFC

$A12345@example.com

is a valid email address, but will not be matched by the above regular expressions as it stands.

- Suggested Reading: http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx

- Regex source: http://www.dzone.com/snippets/ruby-method-extract-emails

Problem

How can I find an email address inside HTML code with Nokogiri? I supose I will need to use regex, but don't know how. Example code ``` <html> <title>Example</title> <body> This is an example text. example@example.com </body> </html> ``` There is an answer covering the case when there is a href to mail_to, but that is not my case. The email addresses are sometimes inside a link, but not always. Thanks

Original source

Related problems