Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp.escape not escaping forward slashes?

Tags:

ruby

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?

like image 857
Cameron Avatar asked Feb 05 '10 03:02

Cameron


People also ask

How do you escape a forward slash in regex?

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).

How do you match a forward slash in regex?

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.

Do dashes need to be escaped 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).


1 Answers

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 '/'
like image 126
Roman Gonzalez Avatar answered Nov 15 '22 18:11

Roman Gonzalez