我有以下的正則表達式和函數來提取電子郵件到一個數組,而它的工作對我來說似乎並不理想。任何關於我如何批准此事的建議?從字符串中提取電子郵件的更紅寶石般的方式?
@emails = []
matches = @text_document.scan(/\+'(\[email protected]\S+|\{(?:\w+, *)+\w+\}@[\w.-]+)'/i)
matches.each {|m| m[0].split(',').each {|email| @emails << email } }
具體我正在尋找的東西比嵌套each'es更好。
乾杯
編輯要完全公平的,因爲我很喜歡這兩個答案,我給他們倆一個公平運行,但由於CONCAT稍快,縮短我將標誌着作爲回答。
require 'benchmark'
CONSTANT = 1
BenchTimes = 1_000_000
EMAILS = "+'[email protected],[email protected]'"
def email
end
def bm_concat
emails = []
EMAILS.scan(/\+'(\[email protected]\S+|\{(?:\w+, *)+\w+\}@[\w.-]+)'/i) do |matches|
matches.each {|m| emails.concat(m.split(','))}
end
end
def bm_inject
emails = []
EMAILS.scan(/\+'(\[email protected]\S+|\{(?:\w+, *)+\w+\}@[\w.-]+)'/i) do |matches|
matches.inject([]) {|arr, mails| emails.concat(mails.split(',')) }
end
end
Benchmark.bmbm do |bm|
bm.report("inject:") { BenchTimes.times { bm_inject } }
bm.report("concat:") { BenchTimes.times { bm_concat } }
end
產生以下的輸出:
Rehearsal -------------------------------------------
inject: 11.030000 0.060000 11.090000 (11.145898)
concat: 9.660000 0.050000 9.710000 ( 9.761068)
--------------------------------- total: 20.800000sec
user system total real
inject: 11.620000 0.060000 11.680000 (11.795601)
concat: 10.510000 0.050000 10.560000 (10.678999)
[不要用正則表達式做(http://stackoverflow.com/questions/201323/using-a-regular-expression-到驗證-的電子郵件地址)。 – Polynomial 2012-07-31 14:09:09
@Polynomial:這個鏈接的電子郵件正則表達式是*可怕的*。我不想成爲圖書館的維護者。 – Linuxios 2012-07-31 14:18:44
同意。找一個圖書館,或者只是希望你沒有像'hGy∂@olé.museum'這樣的地址。 – Linuxios 2012-07-31 14:22:10