如何将split与存储在变量中的正则表达式一起使用?

时间:2019-10-24 06:05:51

标签: ruby-on-rails ruby

在Ruby中,我可以这样分割吗?

my_string = "/(ice cold)|cold/"

"It is ice cold outside.".split(my_string)
#=> ["It is ", " outside"]

"It is cold outside.".split(my_string)
#=> ["It is ", " outside"]

2)获得与上面相同输出的正则表达式应该是什么?

谢谢!

1 个答案:

答案 0 :(得分:3)

split_pattern = /ice cold|cold/ 将匹配“冰冷”和“冷”

我已经省略了()周围的冰冷,因为那样的话,它不会分裂并从数组中删除“冰冷”字符串。同时省略它。

s1 = "it is ice cold outside"
s1.split(split_pattern)
#=> ["it is ", " outside"]
s2 = "it is cold outside"
s2.split(split_pattern)
#=> ["it is ", " outside"]