Code says it all:
teststring = "helloworld$"
string_from_user = "world$"
regexp = Regexp.escape(string_from_user) # assigns "world\\$"
p teststring =~ Regexp.new(regexp) # prints 0 => match found
p teststring =~ /regexp/ # prints nil => no match
That the first one matches is mentioned in the Regexp.escape docs.
But why doesn’t the second version match?
I’m concerned because I need to pass this regexp to third party Ruby code. The string comes from the user, so I want to escape it. Then, in some situations, I might add additional regexp symbols to this user’s string. For example, I might pass "^helloworld\\$" so that third party code would match strings like "helloworld$othercontent".
I am worried that if the third party code uses =~ /regexp/ instead of =~ Regexp.new(regexp), I will be in trouble, because there will be no match as indicated by the code above.
Because
/regexp/is a regexp matching the string"regexp". Perhaps you meant/#{regexp}/?Edit: I take it, from reading your question more fully, that you’re passing a string into third party code that you know will be making a Regexp from that string. In which case, you should be safe. As noted above,
/regexp/cannot possibly be what they’re doing, because it’s just wrong. They must be usingRegexp.new()or something similar.