Ruby - 如何在特定关键字

时间:2015-12-07 06:10:09

标签: ruby regex

我希望拆分字符串以在特定关键字或字符出现之前获取子字符串。例如假设特殊字符为+&以及单词"hello"

因此字符串"He says hello to her""ten + three"以及"the dog & the cat"应该返回:

"He says"以及"ten""the dog"

我一直在使用s.split(/[+,&]/).first,但我无法弄清楚如何获得“你好”的部分。

3 个答案:

答案 0 :(得分:4)

(?=\bhello\b|\+|&)

您可以按此分割并获取第一个组件。参见演示。

https://regex101.com/r/hE4jH0/43

答案 1 :(得分:0)

您可以使用原始方法删除方括号并转义+

my_string.split(/hello|&|\+/).first

答案 2 :(得分:0)

{ name: "George", timestamp: 5 }