dak*_*tau 21 javascript regex sentence
我试图使用javascript的拆分来获取字符串中的句子,但保留分隔符,例如!?.
到目前为止我有
sentences = text.split(/[\\.!?]/);
Run Code Online (Sandbox Code Playgroud)
哪个有效,但不包括每个句子的结尾标点符号(.!?).
有谁知道这样做的方法?
Lar*_*tle 54
你需要使用匹配而不是拆分.
试试这个.
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);
Run Code Online (Sandbox Code Playgroud)
改进了lonemc的答案(改进了Mia Chen的答案,改进了mircealungu的答案):
首先,我们可以u
在末尾添加一个选项来匹配 unicode 字符。换句话说,我们可能希望能够解析德语句子、法语句子等。
其次,我们可以使用“Sentence_Terminal”,而不是对应该结束句子的字符进行硬编码,它是 unicode 标准的一部分。
第三,我们可以使用“ Close_Punctuation ” ,而不是对构成右括号的字符进行硬编码。
第四,我们可以使用“ Final_Punctuation ” ,而不是对构成结束引号的字符进行硬编码。
第五,我们可能不想匹配看起来像枚举的东西。例如:
这是第一句话!这是我谈论 MyEnum.Value1 的第二句话!
为此,我们可以使用前瞻模式来构建匹配:
string.match(/(?=[^])(?:\P{Sentence_Terminal}|\p{Sentence_Terminal}(?!['"`\p{Close_Punctuation}\p{Final_Punctuation}\s]))*(?:\p{Sentence_Terminal}+['"`\p{Close_Punctuation}\p{Final_Punctuation}]*|$)/guy);
Run Code Online (Sandbox Code Playgroud)
这是Regex101.com上正则表达式的链接。
以下是Larry的答案的一个小补充,它也将与paranthetical句子相匹配:
text.match(/\(?[^\.\?\!]+[\.!\?]\)?/g);
Run Code Online (Sandbox Code Playgroud)
应用于:
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!!!"
Run Code Online (Sandbox Code Playgroud)
施舍:
["If he's restin', I'll wake him up!", " (Shouts at the cage.)",
" 'Ello, Mister Polly Parrot!", " (Owner hits the cage.)", " There, he moved!!!"]
Run Code Online (Sandbox Code Playgroud)
试试这个: -
sentences = text.split(/[\\.!\?]/);
Run Code Online (Sandbox Code Playgroud)
?
是正则表达式中的特殊字符,因此需要进行转义.
对不起,我想念你的问题 - 如果你想保留分隔符,那么你需要使用match
不要split
看到这个问题
小智 5
米娅的答案的改进是一个版本,其中还包括没有标点符号的结尾句子:
\nstring.match(/[^.?!]+[.!?]+[\\])'"`\xe2\x80\x99\xe2\x80\x9d]*|.+/g)\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
20428 次 |
最近记录: |