我正在寫一個簡短的類來從文檔中提取電子郵件地址。這是我到目前爲止的代碼:Ruby正則表達式不匹配
# Class to scrape documents for email addresses
class EmailScraper
EmailRegex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
def EmailScraper.scrape(doc)
email_addresses = []
File.open(doc) do |file|
while line = file.gets
temp = line.scan(EmailRegex)
temp.each do |email_address|
puts email_address
emails_addresses << email_address
end
end
end
return email_addresses
end
end
if EmailScraper.scrape("email_tests.txt").empty?
puts "Empty array"
else
puts EmailScraper.scrape("email_tests.txt")
end
我「email_tests.txt」文件看起來像這樣:
[email protected]
[email protected]
[email protected]
當我運行該腳本,我得到的是「空陣」打印輸出。但是,當我啓動irb並輸入上述正則表達式時,電子郵件地址串就會與之匹配,並且String.scan函數返回每個字符串中所有電子郵件地址的數組。爲什麼這在irb中而不是在我的腳本中工作?
+1用於解釋'\ z'和'\ Z'的區別不知道。 – stema