-->

JavaScript的正则表达式的文本拆分成句子,并保持分隔符(Javascript RegExp

2019-06-17 14:50发布

我试图使用JavaScript的拆分来获得句子一个字符串,但保持分隔符如!?。

到目前为止,我有

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

它的工作原理,但不包括对每个句子结束标点符号(!?)。

有谁知道的方式做到这一点?

Answer 1:

您需要使用匹配不分裂。

试试这个。

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);


Answer 2:

下面是一个小除了拉里的答案,将匹配也paranthetical的句子:

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

应用于:

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!!!"

施舍:

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


Answer 3:

试试这个: -

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

? 在正则表达式特殊字符因此需要进行转义。

对不起,我错过读您的问题-如果你想保留分隔符,那么你需要使用matchsplit看这个问题



Answer 4:

在mircealungu的回答略有改善:

string.match(/[^.?!]+[.!?]+[\])'"`’”]*/g);
  • 有没有必要在一开始就开括号。
  • 标点符号,如'...''!!!''!?' 等等都包括内部的句子。
  • 任何数量的方括号接近和关闭括号的也包括在内。 [编辑:加入不同的闭合引号]


文章来源: Javascript RegExp for splitting text into sentences and keeping the delimiter