javascript - 使用 JavaScript 对字符串中的句子进行计数

标签 javascript regex string count coffeescript

已经有几个类似的问题:

我的情况有点不同。

我需要计算字符串中句子的数量。

最接近我需要的答案是:

str.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|")

这里唯一的问题是这个正则表达式假定一个句子以大写字母开头,但情况可能并非总是如此。

更具体地说,我将一个句子定义为:

  • 以字母(大写或非大写)、数字甚至符号(例如 $ 或 €)开头。
  • 以标点符号结尾,例如“.”、“?”或“!”。

但是,如果一个句子包含一个数字,而这个数字本身包含一个“.”或一个“,”,那么该句子应该被视为一个句子而不是两个。

最后但同样重要的是,我们可以假设,除了第一句话,一个句子前面有一个空格。

给定一个随机字符串,我如何用 Javascript(或 CoffeeScript)计算它包含的句子数量?

最佳答案

解决您问题的一个正则表达式是:

\w[.?!](\s|$)

部分内容如下:

\w - Word character
\[.?!] - Punctuation as specified.
(\s|$) - Whitespace character OR the end of the string.

您可以使用字符类而不是组:

[\s|$]

对于最后一个元素,但这不适用于 https://regex101.com/ .

测试了以下内容:

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

并找到六个句子(加粗的句子结尾,而不是实际匹配项)。请注意,如果您出于任何原因依赖它,不同的分组可能会带来问题。

关于javascript - 使用 JavaScript 对字符串中的句子进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215348/

相关文章:

javascript - 如何使 jquery 创建的 div 可拖动?

javascript - ASP.NET MVC Razor 。如何不替换字段 ID 上的非美国字符?

java - 正则表达式从字符串中查找特定模式字符串

函数中的 C++ 段错误

c - 用 C 语言制作 getline()

javascript - Angular 2 路由组件无法正确渲染

javascript - 使用 AJAX 从表单发送所有数据

c# - 允许任何 ASCII 字符的正则表达式模式。但不带空格

java - MongoDb Spring 在嵌套对象中查找

java - 如何使用 or ||... 比较字符串