Javascript RegExp用于将文本拆分为句子并保留分隔符 [英] Javascript RegExp for splitting text into sentences and keeping the delimiter

查看:118
本文介绍了Javascript RegExp用于将文本拆分为句子并保留分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

到目前为止我已经

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

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

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

有没有人知道如何做到这一点?

Does anyone know of a way to do this?

推荐答案

你需要使用匹配不拆分。​​

You need to use match not split.

试试这个。

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

这篇关于Javascript RegExp用于将文本拆分为句子并保留分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆