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.