我想从这句话中提取the cat
和another mat
:
>>> text = "the cat sat on another mat"
>>>
>>> re.findall('(the|another)\s+\w+', text)
['the', 'another']
但是它不会返回后面的cat
和mat
。如果我将其更改为re.findall('another\s+\w+', text)
,那么它将找到该部分,但是(first thing | second thing)
为什么不起作用?
(使用Python的re
模块)
答案 0 :(得分:3)
我会
import re
text = "the cat sat on another mat"
re.findall('the\s+\w+|another\s+\w+', text)
结果应该是
>>> ['the cat', 'another mat']
答案 1 :(得分:2)
re.findall
仅返回捕获组中的子字符串,因此,在这种情况下,您应该使用非捕获组,以便re.findall
将返回整个比赛:
re.findall('(?:the|another)\s+\w+', text)
这将返回:
['the cat', 'another mat']