正则表达式以匹配字符串的句子和单词

时间:2019-09-23 17:32:13

标签: javascript regex regex-group

我想制作一个正则表达式,它可以匹配一个句子和一个匹配单词的单词。       如果为“!”,“?” ,'。'匹配,则将其视为句子的结尾,并且还匹配匹配句子的每个单词。

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

我的正则表达式要分别匹配每个单词:[^\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.

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您在寻找这样的东西吗?

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

答案 1 :(得分: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')

相关问题