【问题标题】:Split paragraph into sentences when paragraph ends with quotes using Javascript使用Javascript将段落以引号结尾时将段落拆分为句子
【发布时间】:2026-01-14 19:55:02
【问题描述】:

我正在尝试使用 Javascript 正则表达式将整个段落拆分为一个句子。

段落:

I visited a bar in Kansas. At the entrance I see, "Welcome to the bar!" While leaving that place I see message, "Good night!" I wondered how they changed the name.

我想把上面的段落拆分成句子。

  1. 我参观了堪萨斯州的一家酒吧。
  2. 在入口处我看到“欢迎来到酒吧!”
  3. 离开那个地方时,我看到消息“晚安!”
  4. 我想知道他们是如何更改名称的。 (“晚安!”之间有一个换行符(<br>),我想知道怎么做..)

目前我正在使用正则表达式

var reg= /(\S.+?[.!?"'] | [.!?] + ["'!.?])(?=\s+[A-Z]|[^<br>]|$)/g;

但它没有将换行符(&lt;br&gt;) 视为单独的句子。它将单词拆分为

  1. 我参观了堪萨斯州的一家酒吧。
  2. 在入口处我看到“欢迎来到酒吧!”
  3. 离开那个地方时,我看到消息“晚安!”我想知道他们是如何改名的。

要创建换行符需要输入Shift+Enter键。

【问题讨论】:

  • var array = yourstring.split(".") 不适合你?
  • jQuery 是一个 DOM 操作库,而不是字符串库!
  • 其实我需要处理所有的场景,任何一个句子都会以 .?!"' 结尾。如果有逗号后跟 " 或 ' 它应该把它当作一个完整的句子。示例:
  • 这个怎么样:/\.|\"\s\n?[A-Z]/。不完全正确,但更接近(将 \n 替换为 br)。

标签: javascript regex


【解决方案1】:

我不确定我是否完全理解您的需要,但这个正则表达式应该可以解决问题

var re = /(\w[^.!?]+[.!?]+"?)\s?/g;

您可以看到matches here(请注意正则表达式右侧的全局g)。我相信它会根据您的需要正确拆分比赛。如果有问题请告诉我。

代码应该类似于(直接取自http://regex101.com

var re = /([^.!?]+[.!?]"?)\s?/g; 
var str = 'I visited a bar in Kansas. At the entrance I see, "Welcome to the bar!" While leaving that place I see message, "Good night!"\nI wondered how they changed the name.';
var m;

while ((m = re.exec(str)) != null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

【讨论】:

  • var re = /([^.!?]+[.!?]"?)\s?/g; 这个正则表达式很适合我。谢谢。
  • 但是当我的句子以“?!”、“!!”、“...”等结尾时会发生什么?
  • 好点。添加一个+ 应该可以解决所有问题。检查链接我的答案