用于将文本拆分为句子并保留分隔符的 Javascript RegExp

新手上路,请多包涵

我正在尝试使用 javascript 的拆分从字符串中获取句子,但保留分隔符,例如 !?。

到目前为止我有

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

哪个有效,但不包括每个句子的结尾标点符号 (.!?)。

有谁知道这样做的方法吗?

原文由 daktau 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 895
2 个回答

您需要使用匹配而不是拆分。

尝试这个。

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

原文由 Larry Battle 发布,翻译遵循 CC BY-SA 3.0 许可协议

以下是对 Larry 的回答的一个小补充,它也将匹配附加句子:

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

原文由 mircealungu 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题