In IRB if I pass a string like "/domain/path" to Regexp.escape it just returns it the same. I thought that forward slashes are supposed to be escaped with a backslash? Am I missing something here?
We should double for a backslash escape a forward slash / in a regular expression. A backslash \ is used to denote character classes, e.g. \d . So it's a special character in regular expression (just like in regular strings).
You need to escape the / with a \ . Show activity on this post. You can escape it by preceding it with a \ (making it \/ ), or you could use new RegExp('/') to avoid escaping the regex.
You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).
Also, the only reason why you would need to escape /
characters is because it is your delimiter for the regexp, if you specify other type of delimiters (or make an instance of the Regexp class) you won't have this issue:
/^hello\/world$/ # escaping '/' just to say: "this is not the end"
%r"^hello/world$" # no need for escaping '/'
Regexp.new('^hello/world$') # no need for escaping '/'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With