首页 > 解决方案 > 正则表达式空匹配 re.findall

问题描述

我想组合多个正则表达式模式。当我这样做时,我注意到在某些情况下会出现空匹配,我不知道这种行为:

import re
s = 'some test set of words'

# if I use round brackets as a capturing group and a or pipe to combine them empty matches appear
re.findall('(some)|(test)', s, flags=re.IGNORECASE)
[('some', ''), ('', 'test')]

# no empty matches by avoiding the round brackets
re.findall('some|test', s, flags=re.IGNORECASE)
['some', 'test']

# no empty matches if round brackets are used with a single pattern.
re.findall('(some)', s, flags=re.IGNORECASE)
['some']

有人可以解释这种行为吗?


文档提到它将包括空匹配项。:

re.findall(pattern, string, flags=0)返回字符串中模式的所有非重叠匹配,作为字符串列表。从左到右扫描字符串,并按找到的顺序返回匹配项。如果模式中存在一个或多个组,则返回组列表;如果模式有多个组,这将是一个元组列表。结果中包含空匹配项。

但这并不能解释这种行为,只是它打算有空匹配。

标签: pythonregex

解决方案


推荐阅读