我正在尝试使用JavaScript的分割来获取字符串中的句子,但保留分隔符例如!?。Javascript正则表达式用于将文本拆分为句子并保留分隔符
到目前为止,我有
sentences = text.split(/[\\.!?]/);
其作品,但不包括对每个句子结束标点符号(!?)。
有谁知道一种方法来做到这一点?
我正在尝试使用JavaScript的分割来获取字符串中的句子,但保留分隔符例如!?。Javascript正则表达式用于将文本拆分为句子并保留分隔符
到目前为止,我有
sentences = text.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);
试试这个: -
sentences = text.split(/[\\.!\?]/);
?
是在正则表达式特殊字符所以需要进行转义。
对不起,我错过读您的问题 - 如果你想保留分隔符,那么你需要使用match
没有split
看到this question
只是一个小提示:像'?'这样的特殊字符不需要在字符类(方括号)内转义。 – JoeRocc 2016-05-06 16:58:39
下面是一个小除了拉里的回答也将匹配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!!!"]
任何想法如何调整这个十进制数?例如。 “在那里,他移动了99.9%!!!” – 2015-09-28 00:52:30
您错过了标点符号字符类'[。!?]'后面的'+',所以在“他移动”之后它不会捕获到三个感叹号。 – Mogsdad 2015-09-28 23:56:08
'? '也是RegExp中的一个特殊字符,因此您需要将其转义 – rgvcorley 2012-08-01 14:37:44
像'.'和'?'这样的元字符在字符类中失去了特殊的含义。匹配点('.'),感叹号('!')或问号('?')的正确方法是'[。!?]'。 – 2013-05-12 07:14:31