正则表达式仅返回比赛的第一部分

时间:2019-01-29 22:12:23

标签: python regex

我想从这句话中提取the catanother mat

>>> text = "the cat sat on another mat"
>>> 
>>> re.findall('(the|another)\s+\w+', text)
['the', 'another']

但是它不会返回后面的catmat。如果我将其更改为re.findall('another\s+\w+', text),那么它将找到该部分,但是(first thing | second thing)为什么不起作用?

(使用Python的re模块)

2 个答案:

答案 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']