Javascript RegExp用于将文本拆分为句子并保留分隔符

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)

  • 这在有浮点数时会中断:`Lorem Ipsum 来自“de Finibus Bonorum et Malorum”的第 1.10.32 和 1.10.33 节` (5认同)
  • 这是一个变体,当最后一个句子没有标点符号结束时也可以使用:`var result = str.match(/([^\.!\?]+[\.!\?++)|([^ \.!\ ?] + $)/克);` (3认同)
  • 正则表达式是错误的.如果我输入:"短语1.短语2.短语3","短语3"被丢弃. (2认同)

Jam*_*mes 9

改进了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上正则表达式的链接。


mir*_*ngu 8

以下是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)


rgv*_*ley 5

试试这个: -

sentences = text.split(/[\\.!\?]/);
Run Code Online (Sandbox Code Playgroud)

? 是正则表达式中的特殊字符,因此需要进行转义.

对不起,我想念你的问题 - 如果你想保留分隔符,那么你需要使用match不要split看到这个问题

  • 只是一个小注释:像`?`这样的特殊字符不需要在字符类(方括号)中进行转义. (2认同)

小智 5

米娅的答案的改进是一个版本,其中还包括没有标点符号的结尾句子:

\n
string.match(/[^.?!]+[.!?]+[\\])'"`\xe2\x80\x99\xe2\x80\x9d]*|.+/g)\n
Run Code Online (Sandbox Code Playgroud)\n