只需要使用 Ruby 代码收集电子邮件

Need to collect only emails using Ruby code

我收到了一份电子邮件列表,我想在其中 运行 开展电子邮件活动,但是,列表中有一些 URL...事物。

这是电子邮件地址的标准格式,例如:

新闻@ydr.com

我想将列表粘贴到终端和 运行 一个命令来只捕获所有电子邮件地址并将它们保存到一个文件并删除任何 URLS。

请指教!非常感谢:)

如果您只是想捕获大多数电子邮件,此正则表达式可能会起作用。 我从这里得到这个正则表达式 How to validate an email address using a regular expression? 他们谈论更复杂的 RFC822 电子邮件正则表达式

 #!/usr/bin/env ruby

input = $stdin.readlines # ctrl + D after paste
input.each do |f|
  puts f if f[/^[a-zA-Z0-9_.+\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/]
end

# test input
# foo@bar.com
# www.cnn.com
# test.email@go.com
# turdburgler@mcdo.net
# http://www.google.com

将电子邮件写入文件:

 #!/usr/bin/env ruby

file = File.open("emails.txt", "w")
input = $stdin.readlines # ctrl + D after paste
input.each do |f|
  file.write(f) if f[/^[a-zA-Z0-9_.+\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/]
end
file.close

需要说明的是,这是一个 ruby 脚本,应该是 运行 这样的。 将脚本保存为文件,即email_parser.rb

chmod +x email_parser.rb
./email_parser.rb # this will wait for stdin, here you paste the list in to the terminal

在终端挂起等待的时候,把邮件列表粘贴进去,然后按ctrl+D告诉程序这是EOF。然后程序将 运行 遍历 emails/urls 的列表并解析。如果使用更新的脚本,其输出将是一个文件。该文件将位于与 运行 脚本相同的文件夹中,并被称为 emails.txt