使用正则表达式在短语中查找单词

时间:2016-01-16 14:57:41

标签: python regex

我想使用正则表达式来查找包含的短语 1 - N个单词中的一个(任何) 2 - 所有N个单词(全部)

>>> import re
>>> reg = re.compile(r'.country.|.place')
>>> phrases = ["This is an place", "France is a European country, and a wonderful place to visit", "Paris is a place, it s the capital of the country.side"]

>>> for phrase in phrases:
...     found = re.findall(reg,phrase)
...     print found
... 

结果:

[' place']
[' country,', ' place']
[' place', ' country.']

似乎我在搞乱,我需要指出我需要找到一个单词,而不仅仅是两个单词中的一部分单词。

任何人都可以指出这个问题吗?

1 个答案:

答案 0 :(得分:0)

因为您要尝试匹配整个单词,请使用\b来匹配单词边界:

reg = re.compile(r'\bcountry\b|\bplace\b')