我正在尝试使用 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);
以下是拉里答案的一个小补充,它也将匹配副句:
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!!!"]
Try this instead:-
sentences = text.split(/[\\.!\?]/);
?
is a special char in regular expressions so need to be escaped.
Sorry I miss read your question - if you want to keep delimiters then you need to use match
not split
see this question
对 mircealungu 的回答略有改进:
string.match(/[^.?!]+[.!?]+[\])'"`’”]*/g);
'...'
,'!!!'
等标点符号。'!?'
在这里改进 Mia 的答案是一个版本,其中还包括没有标点符号的结尾句子:
string.match(/[^.?!]+[.!?]+[\])'"`’”]*|.+/g)