Skip to main content
 首页 » 编程设计

python之正则表达式只返回匹配的第一部分

2025年05月04日28zengkefu

我想从这句话中提取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模块)

请您参考如下方法:

我愿意

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

结果应该是

>>> ['the cat', 'another mat']