Regex problem with match method
I want validate many mails ( one or more) with regex expression but this attribute don´t belongs to any model. So I wrote a method:
def emails_are_valid?(emails)
#regex with validation
regex = Regexp.new("^(\s*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*([,]{1}[\s]*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*)开发者_运维知识库*)$")
#if the quantity of emails is zero o its validations is bad return false.
if emails.blank? || emails.match(regex).nil?
return false
else
return true
end
end
I evaluate this string mm@somedomain.com aa, mma@somedomain.com when I tested this regex in http://www.rubular.com/ is bad (no matches). So According to this page my regex is ok.
But when I evaluate emails.match(regex).nil? that returns me false (So the string is valid, but this string is bad)
Please I need help. my regex is bad or my emails_are_valid? method is bad or match method is bad.
Thanks in advance.
You should have used single quotes instead of double quotes when declaring your regex, otherwise \s
gets parsed as an escape sequence.
Change that line to
regex = Regexp.new('^(\s*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*([,]{1}[\s]*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*)*)$')
and the method will work.
On a side note, this would be a more concise way of doing the same thing - http://codepad.org/YbsqIkcP
精彩评论