Regexp.escape没有逃避正斜杠?

Cam*_*ron 15 ruby

在IRB中如果我将一个像"/ domain/path"这样的字符串传递给Regexp.escape,它就会返回相同的内容.我认为正斜杠应该用反斜杠转义?我在这里错过了什么吗?

Rom*_*lez 26

此外,您需要转义/字符的唯一原因是因为它是regexp的分隔符,如果指定其他类型的分隔符(或创建Regexp类的实例),则不会出现此问题:

/^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 '/'
Run Code Online (Sandbox Code Playgroud)

  • 对于那些因为 Rubular.com 说“必须转义正斜杠”而来这里的人,这是因为 Rubular.com 被硬编码为使用 @Roman Gonzalez 在这个答案中谈到的“/”分隔符。所以在 Rubular.com 上,是的,你确实需要,但 `Regexp.escape` 不需要。 (2认同)