在正则表达式中添加输入变量

时间:2020-02-16 19:24:37

标签: python regex input

我正在尝试编写一个代码,以查找所有首选的文件扩展名,然后将其移动到设计的文件夹中。代码正在工作,但是我需要在文件内部手动输入文件扩展名。我想做的是添加一个输入变量并将其放入re.compile(),因此,无论何时需要不同文件类型的文件,我都无需编辑。

这部分我需要编辑:

# Go through the listFiles and find specific file types.
picRegex = re.compile(r'.*\.jpg|.*\.png')
fileMatches = list(filter(picRegex.match, listFiles)

这适用于代码中已经存在的文件类型,但是正如我所说,我希望它更加灵活。有什么办法可以改善吗?谢谢!

2 个答案:

答案 0 :(得分:0)

正则表达式只是您传递给re.compile和朋友的字符串。完整的Python字符串格式设置可供您使用。

那么也许是这样吗?

picPegex = re.compile('|'.join([r'.*\.{0}'.format(x) for x in ('jpg', 'png')]))

不过,如果您始终需要这些内容,也许只是

if thing.endswith(tuple(['.{0}' for x in ('jpg', 'png')])):
    print('yowza')

答案 1 :(得分:0)

使用字符串方法生成正则表达式:

file_extensions = ['.png','.jpg']
regex = '.*(%s)' % '|'.join(map(re.escape, file_extensions))
filename_matches = list(filter(re.compile(regex).fullmatch, filenames)

更好,根本不使用正则表达式,而是使用endswith

file_extensions = tuple(['.png','.jpg'])
filename_matches = [f for f in filenames if f.endswith(file_extensions)]