Ikbear
Ikbear

Reputation: 1307

extract all email addresses from some .txt documents using ruby

I have to extract all email addresses from some .txt documents. These emails may have these formats:

  1. [email protected]
  2. {a, b, c}@abc.edu
  3. some other formats including some @ signs.

I choose ruby for my first language to write this program, but i don't know how to write the regex. Would someone help me? Thank you!

Upvotes: 1

Views: 12354

Answers (3)

Eskim0
Eskim0

Reputation: 834

Found this at https://www.shellhacks.com/regex-find-email-addresses-file-grep/ which met my needs:

\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b

Upvotes: 1

Jan Goyvaerts
Jan Goyvaerts

Reputation: 21999

Depending on the nature of your .txt documents, you don't have to use one of the complicated regexes that attempt to validate email addresses. You're not trying to validate anything. You're just trying to grab what's already there. Generally speaking, a regex to grab what's already there can be much simpler than a regex that needs to validate input.

An important question is whether your .txt documents contain @ signs that are not part of an email address you want to extract.

This regex handles your first two requirements:

\w+@[\w.-]+|\{(?:\w+, *)+\w+\}@[\w.-]+

Or if you want to allow any sequence of non-space characters containing an @ sign, plus your second requirement (which has spaces):

\S+@\S+|\{(?:\w+, *)+\w+\}@[\w.-]+

Upvotes: 6

Jonathan
Jonathan

Reputation: 26609

Have a look at this rather in-depth analysis:

Upshot is use this regular expression:

/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i

Upvotes: 2

Related Questions