简体   繁体   中英

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. a@abc.com
  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!

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.-]+

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

https://www.shellhacks.com/regex-find-email-addresses-file-grep/上找到了此文件,它满足了我的需求:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM