Home > Back-end >  Regular expression in form of string not working in Ruby
Regular expression in form of string not working in Ruby

Time:12-06

I have regular expressions stored in a variable - s="/\A([^@\s] )@((?:a-b \.) (in|com))\z/".

"[email protected]".match?(/\A([^@\s] )@((?:a-b \.) (in|com))\z/) => returns true
Regexp.new(s) => returns /\/A([^@ ] )@((?:a-b .) (in|com))z\//
"sourabh@a-b.in".match?(Regexp.new(s)) => returns false

While storing the regular expression in the database the \ is removed automatically. I will get the regex validator in the form of a string. Don't know why it is not working?

CodePudding user response:

Use single quotes instead of double quotes (cf this page)

> puts "/\A([^@\s] )@((?:a-b \.) (in|com))\z/"
/A([^@ ] )@((?:a-b .) (in|com))z/

> puts '/\A([^@\s] )@((?:a-b \.) (in|com))\z/'
/\A([^@\s] )@((?:a-b \.) (in|com))\z/

Then remove the starting and ending '/':

> s = '\A([^@\s] )@((?:a-b \.) (in|com))\z'
=> "\\A([^@\\s] )@((?:a-b \\.) (in|com))\\z"

> reg = Regexp.new s
=> /\A([^@\s] )@((?:a-b \.) (in|com))\z/

> "sourabh@a-b.in".match?(Regexp.new(reg))
=> true

CodePudding user response:

When you need to store a regular expression pattern inside a database, a common approach is to store the pattern / flags as a string.

Thus, in case you are going to use a single column to store regex data, you may use Regexp#to_s:

regex_string = /.../.to_s

If you want to store the pattern (source) and flags (options) as separate strings:

regex_pattern = /\A([^@\s] )@((?:a-b \.) (in|com))\z/.source
regex_flags = /\A([^@\s] )@((?:a-b \.) (in|com))\z/.options

Once you read the values from a databse, you can use the Regexp.new constructor to get the regex object back:

rx = Regexp.new(regex_string)
# or
rx = Regexp.new(regex_pattern, regex_flags)

See Regexp Ruby documentation.

  • Related