Reputation: 16724
I have the following code. My intend is to be able to parse the last full sentence in a string of sentences:
string = "something for nothing. 'nothing for free.'"
string.split(/!|\.|\.'|\?/)
=> ["something for nothing", " 'nothing for free", "'"]
I would like to be able to do array.last
and get the last sentence, whether it ends in '!', '?', '.', or the end of a quote like, ." or .'
But when I try to include a combination, as above, it doesn't treat the .'
part as a single delimiter.
Upvotes: 0
Views: 910
Reputation: 100
string = "something for nothing. 'nothing for free.'. Something for free? '...Everything for FREE!!!!!!...' "
string.split(/\b?\.\s|\?\s|\!\s/)
=> ["something for nothing", " 'nothing for free.'", "Something for free", "'...Everything for FREE!!!!!!...' "]
Upvotes: 0
Reputation: 59232
As I can see, there are two spaces between the sentences. So just split on them, instead of using a regex, which is not needed here at all.
puts string.split(" ").last #=> 'nothing for free.'
If punctuation is guaranteed, then you can use the rex
puts string.split(/(?<=[.?!]("|'|))\s+/).last
The regex /(?<=[.?!]("|'|\s))\s+/
uses lookbehind and splits on the space after .
or ?
or !
+ "
or '
or space.
Upvotes: 1