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.
Regexp.new
should NOT work that way, because one could not use "special" regex constructs then. Also, I thinkinclude
will do the same job. Check How to check whether a string contains a substring in Ruby?String::include?
is the best way to match aString
against anotherString
, but I don't think it can output aRegexp
. I buy your point aboutRegexp.new
, though.Regexp
at all to check if a literalString
is present inside anotherString
. That is redundant complication/overhead.[]
allows either fixed strings or regexp, as doesgsub
andsub
. An API that is restrictive when the class itself allows either seems too rigid.escape
method. You could always patch in your ownRegexp.string
method if you like.