Create a case-insensitive regular expression from a string in Ruby
Solution 1:
You can use Regexp.escape
to escape all the characters in the string that would otherwise be handled specially by the regexp engine.
Regexp.new(Regexp.escape("A man + a plan * a canal : Panama!"), Regexp::IGNORECASE)
or
Regexp.new(Regexp.escape("A man + a plan * a canal : Panama!"), "i")
Solution 2:
Ruby regexes can interpolate expressions in the same way that strings do, using the #{}
notation. However, you do have to escape any regex special characters. For example:
input_str = "A man + a plan * a canal : Panama!"
/#{Regexp.escape input_str}/i
Solution 3:
If you know the regular expression you want already, you can add "i" after the expression (eg /the center cannot hold it is too late/i
) to make it case insensitive.
Solution 4:
A slightly more syntactic-sugary way to do this is to use the %r
notation for Regexp literals:
input_str = "A man + a plan * a canal : Panama!"
%r(#{Regexp.escape(input_str)})i
Of course it comes down to personal preference.