我正在尝试获取正确的语法来从单词列表中获取匹配项的数量 示例:
列表:(美国、英国、希腊、德国、尼日利亚、巴西)
文本是:“蛋糕返回将巴西欢迎堆栈放在阿根廷溢出英国段落之间”
我想知道上面列表中有多少单词以正则表达式模式出现在该文本中。 或者,我想知道文本列表中是否有超过 1 个匹配项
是否可以使用正则表达式来做到这一点?
最佳答案
在Python中:
>>> import re
>>> countries = re.compile(r"\b(?:US|UK|Greece|Germany|Nigeria|Brazil)\b")
>>> text = "Cake returns put Brazil Welcome Stack to between paragraphs Argentina Overflow UK"
>>> len(countries.findall(text))
2
说明:
\b # Word boundary (start of word)
(?: # Match either...
US # US
| # or
UK # UK
| # or
Greece # Greece (etc.)
) # End of alternation
\b # Word boundary (end of word)
关于正则表达式:计算单词列表中的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9212674/