/\bword\b|other/ 但是,这样做会导致-6ren">
gpt4 book ai didi

ruby - 在字符串和正则表达式之间转换

转载 作者:数据小太阳 更新时间:2023-10-29 08:57:08 25 4
gpt4 key购买 nike

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

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

但是,这样做会导致 /\x08word\x08|other/

有什么办法可以做到这一点吗?

最佳答案

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

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 的参数(正则表达式本身也可以)。

关于ruby - 在字符串和正则表达式之间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com