Javascript RegExp for splitting text into sentences and keeping the delimiter

Viewed 29702

I am trying to use javascript's split to get the sentences out of a string but keep the delimiter eg !?.

So far I have

sentences = text.split(/[\\.!?]/);

which works but does not include the ending punctuation for each sentence (.!?).

Does anyone know of a way to do this?

6 Answers

A slight improvement on mircealungu's answer:

string.match(/[^.?!]+[.!?]+[\])'"`’”]*/g);
  • There's no need for the opening parenthesis at the beginning.
  • Punctuation like '...', '!!!', '!?' etc. are included inside sentences.
  • Any number of square close brackets and close parentheses are included. [Edit: different closing quotation marks added]

Improving on Mia's answer here is a version which also includes ending sentences with no punctuation:

string.match(/[^.?!]+[.!?]+[\])'"`’”]*|.+/g)

Improving on lonemc's answer (which improved on Mia Chen's answer, which improved on mircealungu's answer):

First, we can stick a u option at the end in order to match unicode characters. In other words, we probably want to be able to parse German sentences, French sentences, etc.

Second, instead of hard-coding the characters that should end a sentence, we can use "Sentence_Terminal", which is part of the unicode standard.

Third, instead of hard-coding the characters that make up a closing bracket, we can use "Close_Punctuation".

Forth, instead of hard-coding the characters that make up a closing quote, we can use "Final_Punctuation".

Fifth, we might not want to match things that look like enums. For example:

This is the first sentence! This is the second sentence with MyEnum.Value1 where I talk about it!

In order to do that, we can compose a match using a lookahead pattern:

string.match(/(?=[^])(?:\P{Sentence_Terminal}|\p{Sentence_Terminal}(?!['"`\p{Close_Punctuation}\p{Final_Punctuation}\s]))*(?:\p{Sentence_Terminal}+['"`\p{Close_Punctuation}\p{Final_Punctuation}]*|$)/guy);

Here's a link to the regex on Regex101.com.

Related