Convert String to Regexp in Ruby

I frequently need to convert a String into a Regexp. For many strings, Regexp.new(string) is sufficient. But if string contains special characters, they need to be escaped:

string = "foo(bar)"
regex = Regexp.new(string) # => /foo(bar)/
!!regex.match(string) # => false

The Regexp class has a nice way to escape all characters that are special to regex: Regexp.escape. It's used like so:

string = "foo(bar)"
escaped_string = Regexp.escape(string) # => "foo\\(bar\\)"
regex = Regexp.new(escaped_string) # => /foo\(bar\)/ 
!!regex.match(string) # => true

This really seems like this should be the default way Regexp.new works. Is there a better way to convert a String to a Regexp, besides Regexp.new(Regexp.escape(string))? This is Ruby, after all.


ANSWERS:


You should never need to run Regexp.new(Regexp.escape(string)) This is because, in Core and StdLib, practically every method that takes a Regexp also takes a String (as it should).

In the original case, if you're trying to match a big String big_string on a wacky string with special characters like "foo(bar)", you can just run big_string.match("foo(bar)").

If you're trying to do something fancier, you might need use both ::escape and ::new, but never in direct composition. For example, if we want to match big_string on a wacky string followed by a lone digit, we'll run Regexp.new(Regexp.escape(string) + "\\d").



 MORE:


 ? Array includes string ruby?
 ? How do I check if a string contains a specific word?
 ? How do I check if a string contains a specific word?
 ? How do I check if a string contains a specific word?
 ? PHP - How to check if a string contain any text
 ? PHP - How to check if a string contain any text
 ? PHP - How to check if a string contain any text
 ? PHP - How to check if a string contain any text
 ? How do I check if a string contains a specific word?
 ? How can I check if a word is contained in another string using PHP?