Javascript RegExp for splitting text into sentence

2019-01-07 12:21发布

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?

3条回答
SAY GOODBYE
2楼-- · 2019-01-07 12:38

You need to use match not split.

Try this.

var str = "I like turtles. Do you? Awesome! hahaha. lol!!! What's going on????";
var result = str.match( /[^\.!\?]+[\.!\?]+/g );

var expect = ["I like turtles.", " Do you?", " Awesome!", " hahaha.", " lol!!!", " What's going on????"];
console.log( result.join(" ") === expect.join(" ") )
console.log( result.length === 6);
查看更多
家丑人穷心不美
3楼-- · 2019-01-07 12:48

The following is a small addition to Larry's answer which will match also paranthetical sentences:

text.match(/\(?[^\.\?\!]+[\.!\?]\)?/g);

applied on:

text = "If he's restin', I'll wake him up! (Shouts at the cage.) 
'Ello, Mister Polly Parrot! (Owner hits the cage.) There, he moved!!!"

giveth:

["If he's restin', I'll wake him up!", " (Shouts at the cage.)", 
" 'Ello, Mister Polly Parrot!", " (Owner hits the cage.)", " There, he moved!!!"]
查看更多
对你真心纯属浪费
4楼-- · 2019-01-07 12:59

Try this instead:-

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

? is a special char in regular expressions so need to be escaped.

Sorry I miss read your question - if you want to keep delimiters then you need to use match not split see this question

查看更多
登录 后发表回答