Rails:匹配后截断字符串

时间:2013-08-15 23:51:55

标签: ruby-on-rails regex ruby-on-rails-3

说我有一个像这样的字符串:

"This belongs to that then there's this other keyword which does something else."

我如何截断它以便它找到keyword并截断keyword which does something else.只给我:

"This belongs to that then there's this other "

谢谢!

2 个答案:

答案 0 :(得分:1)

1.9.3p327 > str = "This belongs to that then there's this other keyword which does something else."
 => "This belongs to that then there's this other keyword which does something else."
1.9.3p327 > str.sub(/keyword.*/, '')
 => "This belongs to that then there's this other "

要小心,因为这也会匹配“keywordwithnotrailingspace”。查看\ b获取单词边界...

答案 1 :(得分:1)

添加到工具栏的简单工具是Rubular。你可以在你的浏览器中测试各种令人敬畏的正则表达式...教一个人钓鱼...你知道这句话。 :)

@emm - 我认为@ Philip的回答是正确的;但是,我会使用两个答案的组合,并使用keyword[.|\s]*