python - 正则表达式空匹配 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)
返回字符串中模式的所有非重叠匹配,作为字符串列表。从左到右扫描字符串,并按找到的顺序返回匹配项。如果模式中存在一个或多个组,则返回组列表;如果模式有多个组,这将是一个元组列表。结果中包含空匹配项。
但这并不能解释这种行为,只是它打算有空匹配。
解决方案
推荐阅读
- rust - Mutex中的可变借用失败
- javascript - 如何让两个输入都与搜索栏一起使用?
- javascript - 使用反应的进度条
- heroku - Heroku 帐户因内置身份验证而锁定失败
- python - discord.py TypeError:对象锁不能用于“等待”表达式
- unity3d - 切换 ARFoundatin (ARCore / ARKit) <-> Google Cardboard 不起作用
- javascript - 如何添加到数组其他数组
- c# - 在不同环境的 Windows 服务中发布 ASP.Net Core
- database - 通过终端设置 Magento 时数据库连接被拒绝
- c - 低功耗模式下的变量