Create a case-insensitive regular expression from a string in Ruby

Viewed 36416

Let's say that I have an arbitrary string like

`A man + a plan * a canal : Panama!`

and I want to do a regex search for strings that are the same other than case. That is, this regular expression should match the string

`a man + A PLAN * a canal : PaNaMa!`

I take it the best approach is to backslash-escape every character with a special meaning in Ruby regular expressions, and then do Regexp.new with that string and Regexp::IGNORECASE as arguments. Is that right? Is there a tried-and-true regular expression for converting arbitrary strings into literal regular expressions?

By the way, I ultimately want to use this regular expression to do an arbitrary case-insensitive MongoDB query. So if there's another way I could be doing that, please let me know.

4 Answers
Related