<分区>
我正在尝试使用正则表达式从字符串中提取给定的单词:
>>> pattern = re.compile(ur'(今天|不错)', re.UNICODE)
>>> print pattern.search(u'今天天气不错').groups()
(u'\u4eca\u5929',)
如你所见,只有第一个词被匹配,这里有什么问题吗?
<分区>
我正在尝试使用正则表达式从字符串中提取给定的单词:
>>> pattern = re.compile(ur'(今天|不错)', re.UNICODE)
>>> print pattern.search(u'今天天气不错').groups()
(u'\u4eca\u5929',)
如你所见,只有第一个词被匹配,这里有什么问题吗?
最佳答案
我想你在找re.findall()
>>> print pattern.findall(u'今天天气不错')
[u'\u4eca\u5929', u'\u4e0d\u9519']
findall()
将返回字符串中模式的所有匹配项。
哪里是re.search()
将只返回字符串中的第一个匹配项:
Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance.
关于python - 使用正则表达式从字符串中提取所有匹配的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30747903/