首页 > 解决方案 > 用 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

标签: pythonregex

解决方案


您可以在其中一种选择中删除.?,因为它不会影响匹配并在匹配时连接组值:

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)

查看Python 演示

我看到您需要在每个字符串中获取第一个匹配项,因此,使用re.findall返回所有多个匹配项re.search就足够了。


推荐阅读