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

标签 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模块)

最佳答案

我愿意

import re
text = "the cat sat on another mat"

re.findall('the\s+\w+|another\s+\w+', text)

结果应该是

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

关于python - 正则表达式只返回匹配的第一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54430412/

相关文章:

python - 递归逆 FFT

python - 将字符串转换为 int python

python - lxml 去除 <head> 中的空格和换行符

c# - 如果给定模式,是否有可以生成随机正则表达式字符串的类?

C# Regex.Replace 匹配相同数量的字符

python - 在 Python 中查找文本中所有出现的整数

python - 如何自动对 pandas 数据框的行进行重复计算?

python - Pandas - 将一列中的整数映射到新列中的字符串

python - 非固定长度的正则表达式负回顾

java - 在 Cucumber 步骤定义上传递多个参数