用于文件名约定匹配的正则表达式

2024-10-02 22:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的python脚本执行以下操作:

  1. 从用户获取根目录输入。你知道吗
  2. 扫描所有子目录中的图像文件。你知道吗
  3. 创建所有合法文件名的列表。你知道吗

如果合法文件扩展名是:

"<DDMMYY>\<a 6 letter word>\<a 8 letter OR digit word>\<coutner>_Plot<3 digit number>_row<3 digit number>.jpg"

例如:

"190419\yotamr\yotam123\0001_Plot003_row004.jpg"

我使用.json作为配置文件,因此我希望有一个条目来保存文件扩展名格式的regEx值。你知道吗

我提供了以下正则表达式:

FORMAT = r'([0-3][0-9][0-1][0-9][0-9][0-9])\\([a-zA-Z]{6})\\([a-zA-Z0-9]{8})\\\\d{4}_Plot\\d{3}_row\\d{3}\\.[jpeg]'

不过,每次运行附加的代码时,我总是从re.match()得到“None”作为输出

match = re.match(FORMAT, "190419\yotamr\yotam123\0001_Plot003_row004.jpg")
print(match)

有什么改变的想法吗?你知道吗


Tags: 文件formatnumberplotmatchwordrowjpg
2条回答

您的regexp中有错误。以下是正确的:

FORMAT2 = re.compile(r'([0-3][0-9][0-1]([0-9]{3}))\\([a-zA-Z]{6})\\([a-zA-Z0-9]{8})\\([0-9]{4})_Plot([0-9]{3})_row([0-9]{3})\.jpe?g')
>>> print(re.search(FORMAT2, "190419\\yotamr\\yotam123\\0001_Plot003_row004.jpg"))

<_sre.SRE_Match object; span=(0, 46), match='190419\\yotamr\\yotam123\\0001_Plot003_row004.jpg>

另外,不要忘记在regexp字符串中使用r谓词:r'WAKA[0-9]WAKA'并转义您正在检查的字符串(例如,使用r谓词或手动转义),因为您的字符串:

"190419\yotamr\yotam123\0001_Plot003_row004.jpg"
                       ^
                 here |

包含转换为'\x00'的空字节'\0'。你知道吗

import re

text = "190419\\yotamr\\yotam123\\0001_Plot003_row004.jpg"

format = r"[0-9][0-9][0-9][0-9][0-9][0-9]\\[a-zA-Z]{6}\\[a-zA-Z0-9]{8}\\[0-9]{4}_Plot[0-9]{3}_row[0-9]{3}.jpg"

result = re.search(format, text)

print(result)

相关问题 更多 >