提取可选数量的单词



我有一个这样的字符串-

string="John has got 6 cats but I think my friend Susan has 3 dogs and Mike has 8 fishes"

我想写正则表达式来提取后面的模式名称动词和宠物的数量以及它是什么类型的宠物。

re.findall('[A-Za-z]+ w+ d+ w+', string)

与CCD_ 1配合使用。

但它不适用于John has got 6 cats

如何编辑代码,使其在名称后查找一两个单词?

提前谢谢!

您可以使用非捕获组(?:。。。CCD_ 4和CCD_

import re
string="John has got 6 cats but I think my friend Susan has 3 dogs and Mike has 8 fishes"
found=re.findall(r'[A-Z][a-z]+ (?:w+ ){1,2}d+ w+', string)
print(found)

输出

['John has got 6 cats', 'Susan has 3 dogs', 'Mike has 8 fishes']

相关内容

  • 没有找到相关文章

最新更新