Reputation: 2881
I am new to regex and need to parse a comma-separated input of email address extensions (everything after the @ symbol). Example:
foo.bar,foo.bar.baz,foo-bar.baz
I know that there are no whitespaces in the string. Also. following is the regex I want to use for just a single email extension:
/[a-z\d\-.]+\.[a-z]+\z/i
How do I modify the regex in Ruby to work with multiple extensions which are comma separated?
Thanks!
Upvotes: 0
Views: 1924
Reputation: 461
\A(([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})[, ]?)*\Z
The above regular expression works for 0 or more number of email addresses separated b commas. You may like to chomp (",") the string before saving or using it to remove the trailing comma.
Upvotes: 2
Reputation: 434685
You're probably better of splitting the list into components and then checking each component:
hosts = 'foo.bar,foo.bar.baz,foo-bar.baz'
all_ok = true
hosts.split(/\s*,\s*/).each do |host|
all_ok = false unless(host =~ /[a-z\d\-.]+\.[a-z]+\z/i)
end
That may not be a one-liner but it will probably be a lot easier to understand six months down the road (unless, of course, your regex-fu gets stronger).
Upvotes: 0
Reputation: 14211
try
/(,{0,1}[a-zA-Z_]+[^.]*\.[a-zA-Z]{2,6})+/i
based on my test:
p 'True' if 'foo.bar,foo.bar.baz,foo-bar.baz' =~ /(,{0,1}[a-zA-Z_]+[^.]*\.[a-zA-Z]{2,6})/i
will give
True
Upvotes: 0