我如何划分ruby&split;'有多个分隔符?

时间:2015-01-30 06:22:17

标签: ruby regex

我有以下代码。我的意图是能够用一串句子解析最后一个句子:

string = "something for nothing.  'nothing for free.'"
string.split(/!|\.|\.'|\?/)
=> ["something for nothing", "  'nothing for free", "'"]

我希望能够array.last并获得最后一句话,无论是否结束于'!','?',' 。'或报价的结尾,如。"或。'

但是当我尝试包含一个组合时,如上所述,它并没有将.'部分视为单个分隔符。

2 个答案:

答案 0 :(得分:1)

我可以看到,句子之间有两个空格。所以只需要拆分它们,而不是使用正则表达式,这在这里根本不需要。

puts string.split("  ").last #=> 'nothing for free.'

如果保证标点符号,则可以使用rex

puts string.split(/(?<=[.?!]("|'|))\s+/).last

正则表达式/(?<=[.?!]("|'|\s))\s+/使用lookbehind并在.?! + "'或空格后拆分空格。

答案 1 :(得分:0)

string = "something for nothing.  'nothing for free.'. Something for free? '...Everything for FREE!!!!!!...' "

string.split(/\b?\.\s|\?\s|\!\s/)
  

=&GT; [&#34;什么都没有&#34;,&#34;没有任何免费的东西。&#39;&#34;,&#34;免费的东西&#34;,&#34;&#39; ...一切都是免费的!!!!!! .. 。&#39; &#34;]