首先将要匹配的电子邮件和域名转换为小写,然后使用find_all
正则表达式匹配。
您可以使用find
仅检索第一个匹配的“规则”。
email = 'bob@luv.southwest.com'
domain_rules = [/craigslist.org/, /evite.com/, /ziprealty.com/, /alleyinsider.com/, /fedexkinkos.com/, /luv.southwest.com/, /fastsigns.com/, /experts-exchange.com/, /feedburner.com/]
user, domain = email.split('@').collect { |s| s.downcase }
p domain_rules.find_all { |rule| domain[rule] }
实际上,Regexp并不是必需品:
email = 'bob@luv.southwest.com'
matchable_domains = %w{ craigslist.org evite.com ziprealty.com alleyinsider.com fedexkinkos.com luv.southwest.com fastsigns.com experts-exchange.com feedburner.com }
user, domain = email.downcase.split('@')
p matchable_domains.find_all { |rule| matchable_domains.include?(domain) }
或者,你可以只使用正则表达式:
email = 'bob@luv.southwest.com'
regexp = /[A-Z0-9._%+-]+@(craigslist\.org|evite\.com|ziprealty\.com|alleyinsider\.com|fedexkinkos\.com|luv\.southwest\.com|fastsigns\.com|experts-exchange\.com|feedburner\.com)/
p regexp === email # => true
p regexp.match(email) # => #<MatchData "bob@luv.southwest.com" 1:"bob" 2:"luv.southwest.com">il
/\bcraigslist.org\b|\bbevite.com\b|\bziprealty.com\b/i
http://rubular.com/r/aF5Dhv4CFa - Ollie.
通配符没有被转义。必须对它们进行转义才能正确地工作。 - the Tin Man.
将需要转义...\.
- Ollie