How can I get the "!" as an item on this split list?

Viewed 69

This is my first question!

What should the pattern be in order to make the last "!" appear as an item on this split list?

    import re
    re.split(r'([.?!]) ', 'One sentence. Another one? And the last one!')

I get: ['One sentence', '.', 'Another one', '?', 'And the last one!'], or ['One sentence', '.', 'Another one', '?', 'And the last one', '!', ''] if I use ([.?!]) ?. But I'd like to get this list: ['One sentence', '.', 'Another one', '?', 'And the last one', '!']

Thank you!

1 Answers

You can split using the following regex:

(?=[\.?!])|(?<=[\.?!] )

which will match

  • (?=[\.?!]): any place which is followed by a punctuation character
  • (?<=[\.?!] ): any place which comes after a punctuation character + space

Check the demo here.


Another option is to use a matching operation on all the strings and all the punctuation symbols:

[^\.?!]+(?=[\.?!])|[\.?!]

This will match two patterns:

  • [^\.?!]+(?=[\.?!]): any string [^\.?!]+, followed by a punctuation symbol (?=[\.?!])
  • [\.?!]: the punctuation symbol

Check the demo here.

Related