在String和Regexp之间转换

时间:2018-04-09 19:51:58

标签: ruby

我需要在Regexp的字符串表示和Regexp本身之间来回转换。

这样的事情:
> Regexp.new "\bword\b|other
=> /\bword\b|other/

但是,这样做会产生/\x08word\x08|other/

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:2)

使用单引号,或转义反斜杠。

p re = Regexp.new('\bword\b|other') # => /\bword\b|other/
p re = Regexp.new("\\bword\\b|other")  # => /\bword\b|other/

p re.to_s  # => "(?-mix:\\bword\\b|other)"
p re.inspect # => "/\\bword\\b|other/"

结果字符串to_s可以用作Regexp.new的参数(正则表达式本身也可以)。

相关问题