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