python - 用 or 逻辑重新查找
问题描述
使用“|”时,我得到了 2 个项目的列表 在正则表达式 findall 中,其中一个是空白的
我尝试更改正则表达式格式几次,但没有任何效果。这是我在尝试不同的变体后所拥有的:
示例文件名:
231_HELLO_01.jpg
01_HELLO_WORLD.jpg
HELLO_01_WORLD.jpg
代码
pattern = '_(\d{2}).?|^(\d{2})_'
finddupe = re.findall(pattern, filename)
输出看起来像这样
[('01', '')]
[('02', '')]
[('01', '')]
[('02', '')]
[('01', '')]
[('02', '')]
[('03', '')]
[('04', '')]
[('05', '')]
[('06', '')]
[('07', '')]
[]
我只是想获得没有空字符串和列表的数字。
寻找:
01
02
01
03
04
解决方案
您可以在其中一种选择中删除.?
,因为它不会影响匹配并在匹配时连接组值:
import re
pattern = re.compile('^(\d{2})_|_(\d{2})')
m = pattern.search('12_text')
finddupe = ""
if m:
finddupe = f"{m.group(1) or ''}{m.group(2) or ''}"
# finddupe = "{}{}".format(m.group(1) or '', m.group(2) or '') # for Python versions not supporting interpolation
print(finddupe)
我看到您需要在每个字符串中获取第一个匹配项,因此,使用re.findall
返回所有多个匹配项re.search
就足够了。
推荐阅读
- javascript - 让两个过滤表下拉列表同时工作
- typescript - 有条件申请?每个属性的映射类型中的修饰符
- python - 如何在 python 中替换均值而不是缺失值
- javascript - 这段代码中的选择数组发生了什么?
- reactjs - 从外部 json 文件中获取数据并在 reactjs 应用程序中将其设置为全局
- azure - Azure 逻辑应用程序中的 Azure Function Produce 404
- html - 如何仅使用 css 在 reactjs 中的两个 div 列之间居中此 div
- python - 使用 Flask Heroku 更新 prod postgresql db
- flutter - 无法加载图片资源
- winapi - 使用 GetDIBits() 获取像素 RGB 颜色值