How to make a regex to match all internet domains regardless of the extention

Go To StackoverFlow.com

2

I need to a model validation to block personal email accounts.

I have the following:

PERSONAL_DOMAINS = %w[
 yahoo.
 ymail
 verizon
]

The regex validation:

:format => {
  :without => /#{PERSONAL_DOMAINS.map{|a| Regexp.quote(a)}.join('|')}/
}

The reason yahoo has a dot at the end is to allow yahoo-inc.com but block all the personal domains like yahoo.com, yahoo.fr, yahoo.uk etc...

This regex is failing and causing yahoo-inc.com to get rejected... Any suggestions on how this can be updated to make the use case above pass? Thanks

2012-04-04 01:21
by Rachela Meadows
Can't reproduce, the regex doesn't (and shouldn't) match "yahoo-inc.com" - Niklas B. 2012-04-04 01:27


2

Try doing your match without Rails to help narrow down what's happening:

PERSONAL_DOMAINS_REGEXP = /#{PERSONAL_DOMAINS.map{|a| Regexp.quote(a)}.join('|')}/
=> /yahoo\.|ymail|verizon/

"yahoo-inc.com".match(PERSONAL_DOMAINS_REGEXP)
=> nil

"yahoo.com".match(PERSONAL_DOMAINS_REGEXP)
=> #<MatchData "yahoo.">
2012-04-04 01:37
by joelparkerhenderson


0

Try the following regex:

/(^|\.)(#{PERSONAL_DOMAINS.map{|a| Regexp.quote(a)}.join('|')})\.[^.]+$/i

This will match all domains whose second component is exactly one of the list.

so it will match:

yahoo.com
Yahoo.fr
sub.yahoo.id

etc, but not

yahoo-inc.com
notyahoo.com
yahoo.other.com

(change "yahoo." back to "yahoo")

Note also the "/i" at the end. domains are case-insensitive, so you will need this.

2012-04-04 10:43
by Michael Slade