简体   繁体   中英

ruby on rails validation regex comma separated email addresses

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!

\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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM