How do I keep the delimiters when splitting a Ruby string?

后端 未结 5 612
慢半拍i
慢半拍i 2020-11-29 04:12

I have text like:

content = \"Do you like to code? How I love to code! I\'m always coding.\" 

I\'m trying to split it on either a ?

5条回答
  •  误落风尘
    2020-11-29 05:02

    The most robust way to do this is with a Natural Language Processing library: Rails gem to break a paragraph into series of sentences

    You can also split in groups:

    @content.split(/(\?+)|(\.+)|(!+)/)
    

    After splitting into groups, you can join the sentence and delimiter.

    @content.split(/(\?+)|(\.+)|(!+)/).each_slice(2) {|slice| puts slice.join}
    

提交回复
热议问题