【发布时间】:2012-02-03 14:28:05
【问题描述】:
代码说明一切:
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
Regexp.escape 文档中提到了第一个匹配项。 但是为什么第二个版本不匹配呢?
我很担心,因为我需要将此正则表达式传递给第三方 Ruby 代码。该字符串来自用户,所以我想转义它。然后,在某些情况下,我可能会在该用户的字符串中添加额外的正则表达式符号。例如,我可能会传递"^helloworld\\$",以便第三方代码匹配"helloworld$othercontent" 之类的字符串。
我担心如果第三方代码使用=~ /regexp/而不是=~ Regexp.new(regexp),我会遇到麻烦,因为上面的代码显示不匹配。
【问题讨论】:
标签: ruby regex string escaping