我试图使用JavaScript的拆分来获得句子一个字符串,但保持分隔符如!?。
到目前为止,我有
sentences = text.split(/[\\.!?]/);
它的工作原理,但不包括对每个句子结束标点符号(!?)。
有谁知道的方式做到这一点?
我试图使用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);
下面是一个小除了拉里的答案,将匹配也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!!!"]
试试这个: -
sentences = text.split(/[\\.!\?]/);
?
在正则表达式特殊字符因此需要进行转义。
对不起,我错过读您的问题-如果你想保留分隔符,那么你需要使用match
不split
看这个问题
在mircealungu的回答略有改善:
string.match(/[^.?!]+[.!?]+[\])'"`’”]*/g);
'...'
, '!!!'
, '!?'
等等都包括内部的句子。