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

时间:2019-04-19 10:11:58

标签: python regex python-3.x

我的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()的输出中得到“无”

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

有什么使之生效的想法吗?

2 个答案:

答案 0 :(得分:3)

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)

答案 1 :(得分:0)

您的正则表达式中有错误。这是正确的:

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>

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

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

包含一个空字节'\0',该字节将转换为'\x00'