12
在IRB中,如果我将类似“/ domain/path”的字符串传递给Regexp.escape,它就会返回相同的结果。我认为正斜杠应该用反斜杠逃脱?我在这里错过了什么吗?Regexp.escape不能逃避正斜杠?
在IRB中,如果我将类似“/ domain/path”的字符串传递给Regexp.escape,它就会返回相同的结果。我认为正斜杠应该用反斜杠逃脱?我在这里错过了什么吗?Regexp.escape不能逃避正斜杠?
此外,您需要转义/
个字符的唯一原因是因为它是您的正则表达式的分隔符,如果指定了其他类型的分隔符(或者创建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 '/'
Regexp.new(Regexp.escape('/domain/path'))
=> /\/domain\/path/
OR
Regexp.new(Regexp.escape('domain/path'))
=> /domain\/path/
对于那些来到这里是因为Rubular.com说''正斜线必须被转义。'',这是因为Rubular.com被硬编码为使用@Roman Gonzalez在这个答案中谈到的分界符。所以在Rubular.com上,是的,你确实需要,但是'Regexp.escape'不需要。 – 2016-06-29 12:50:48