我希望拆分字符串以在特定关键字或字符出现之前获取子字符串。例如假设特殊字符为+
和&
以及单词"hello"
。
因此字符串"He says hello to her"
和"ten + three"
以及"the dog & the cat"
应该返回:
"He says"
以及"ten"
和"the dog"
。
我一直在使用s.split(/[+,&]/).first
,但我无法弄清楚如何获得“你好”的部分。
答案 0 :(得分:4)
答案 1 :(得分:0)
您可以使用原始方法删除方括号并转义+
:
my_string.split(/hello|&|\+/).first
答案 2 :(得分:0)
{ name: "George", timestamp: 5 }