【问题标题】:Regex to match a sentence and word of a string正则表达式匹配字符串的句子和单词
【发布时间】:2019-09-23 17:32:13
【问题描述】:

我想制作一个正则表达式,它可以匹配一个句子和匹配句子的单词。 如果 '!', '?' , '.'匹配然后它被视为句子的结尾,它还匹配匹配句子的每个单词。

我的正则表达式匹配句子:[^?!.]+

我的正则表达式分别匹配每个单词:[^\s]+

但是,我不能加入这两个正则表达式来做到这一点。

...测试字符串...

I am Raktim Banerjee. I love to code.

应该返回

2 sentence 8 words

 Stackoverflow is the best coding forum. I love stackoverflow!

应该返回

2 sentence 9 words.

提前感谢您的帮助。

【问题讨论】:

  • dot 可以出现在句子中,也可以作为首字母缩写词和 jr, Mr 等后缀
  • 不要试图一次做所有事情。只需匹配句子,然后forEach 句子,将其拆分为单词。
  • @PrasadTelkikar 我已经给了我两个尝试过的正则表达式,一个用于匹配句子,另一个用于单词。
  • @NiettheDarkAbsol 是的,有很多方法可以做同样的事情。但我想学习正则表达式。这就是为什么...
  • @anubhava 是的,这是另一个问题。即使我写了一个电子邮件地址,那么'。也视为字符串的结尾。我标记了这一点。

标签: javascript regex regex-group


【解决方案1】:

我相信你说过你想要在 JavaScript 中这样做:

var s = 'I am Raktim Banerjee. I love to code.'

var regex = /\b([^!?. ]+)(?:(?: +)([^!?. ]+))*\b([!?.])/g
var m, numSentences = 0, numWords = 0;
do {
    m = regex.exec(s);
    if (m) {
        numSentences++;
        numWords += m[0].split(' ').length
    }
} while (m);
console.log(numSentences + ' sentences, ' + numWords + ' words')

这是第二次迭代。我修改了正则表达式以识别一些称呼,先生、夫人和博士(您可以添加额外的),并添加一个原始的子正则表达式来识别电子邮件地址。而且我还稍微简化了原始的正则表达式。我希望这会有所帮助(无法保证,因为电子邮件检查过于简化):

var s = 'Mr. Raktim Banerjee. My email address is x.y.z@nowhere.com.'

var regex = /\b((Mrs?\.|Dr\.|\S+@\S+|[^!?. ]+)\s*)+([!?.])/g
var m, numSentences = 0, numWords = 0;
do {
    m = regex.exec(s);
    if (m) {
        numSentences++;
        numWords += m[0].split(' ').length
    }
} while (m);
console.log(numSentences + ' sentences, ' + numWords + ' words')

【讨论】:

  • 是的,我确实想要那样,但问题是当 '.'进来一句话。像先生。拉克蒂姆·班纳吉。应该返回 2 个句子 3 个单词。但是,它实际上是 1 个句子和 3 个单词。当我输入任何电子邮件地址时也会出现此问题,因为电子邮件地址带有“。” example@abc.com
【解决方案2】:

你在寻找这样的东西吗:

import re
s1="I am Raktim Banerjee. I love to code. "
s2="Stackoverflow is the best coding forum. I love stackoverflow! "

print(len(re.compile("[^?!.]+").findall(s1))-1,"sentence",len(re.compile("[^\s]+").findall(s1)),"words")

print(len(re.compile("[^?!.]+").findall(s2))-1,"sentence",len(re.compile("[^\s]+").findall(s2)),"words")

运行以上输出:

2 sentence 8 words
2 sentence 9 words

【讨论】:

  • 嗯,我想要这样,输出符合我的预期。但我看不懂代码。
  • 太棒了! “findall” 将匹配所有模式,“len” 将计算编号。的比赛。由于最后一个(。或!或?)将创建一个额外的拆分,因此必须为句子计数做-1。正如你在正则表达式中提到的那样,字数就是这样。
  • 先生,import re 是什么意思?
  • 这是用于导入正则表达式包。
  • 好的。但这是在 python 上。我想在 JS 上做。
猜你喜欢
  • 2021-05-23
  • 1970-01-01
  • 2011-12-13
  • 2022-07-20
  • 2010-12-29
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 2016-12-06
相关资源
最近更新 更多