So, I am trying to apply regular expression to email addresses coming into a site I am working on to try and verify that they are mostly valid. The regular expression is the one below.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@
(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])
When put into ruby as below.
if email =~ [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@ (?:[a-z0-9]
(?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])
#logic here if regex passes
end
The problem is that the regular expression below contains '#' characters which are understood as comments in ruby. So, is there a way to use the regular expression without the '#' being interpreted as comments? Can regular expression be stored as strings or something similar?
You have to use ruby regex syntax /regex/
, or build new regexp with Regexp.new(string)
regexp = /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])/
if email =~ regexp
#logic here if regex passes
end
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.