Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this regex rule case insensitive

I'm doing the following:

email = '[email protected]'

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('@')

domain_rules.each { |rule| return true if !domain.match(rule).nil? }

Problem is this is case sensitive. Is there a way to make this all case insensative, without having to add /i to the end of every single rule?

like image 306
AnApprentice Avatar asked May 01 '11 22:05

AnApprentice


3 Answers

Use the option "i" (ignore case)

domain_rules = [
  /craigslist.org/i,
  /evite.com/i,
  /ziprealty.com/i,
  /alleyinsider.com/i,
  /fedexkinkos.com/i,
  /luv.southwest.com/i,
  /fastsigns.com/i,
  /experts-exchange.com/i,
  /feedburner.com/i
]

test it here... http://rubular.com/

like image 128
Ollie Avatar answered Nov 15 '22 15:11

Ollie


downcase the email & domain you want to match first, then find_all regexp matches.

You can use find to only retrieve the first matching "rule".

email = '[email protected]'

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] }

There's also no real need for Regexp:

email = '[email protected]'

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) }

Or, you can do ONLY Regexp:

email = '[email protected]'
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 "[email protected]" 1:"bob" 2:"luv.southwest.com">il
like image 3
RyanScottLewis Avatar answered Nov 15 '22 15:11

RyanScottLewis


No need to use regexes for simple string comparisons.

email = '[email protected]'

domains = %w(CraigsList.org evite.com ZiPreAltY.com alleyinsider.com fedexkinkos.com luv.southwest.com fastsigns.com experts-exchange.com feedburner.com)

user, user_domain = email.split('@')

p domains.any? { |domain| domain.casecmp(user_domain).zero? }

String#casecmp does a case-insensitive comparison.

like image 2
steenslag Avatar answered Nov 15 '22 14:11

steenslag