0. 正则匹配文件


def getDirFiles(directory,filenamelike,extnames=None):
    '''将文件搜索匹配规则转成正则匹配规则串,主要是*、?和.的处理
           *:匹配0或多个字符
           ?:匹配一个字符
           .:文件前缀、后缀分隔符
           directory:搜索目录
           filenamelike:文件名搜索模式,可以带*和?搜索
           extnames:限定文件名后缀范围,不同后缀分号分隔
           返回值:符合搜索条件的文件名列表
    '''
    import os
    import re

    searchpattern = None
    extnamesList = []
    def transFileMatchToReMatch(matchinf):
        reexprlist = []
        for ch in matchinf:
            if ch=='.':
                reexprlist.append('[.]{1}')
            elif ch=='*':
                reexprlist.append('(.)*')
            elif ch=='?':
                reexprlist.append('(.){1}')
            else:reexprlist.append(ch)
        pattern = ''.join(reexprlist)

        searchpat = re.compile(pattern,re.I)
        return searchpat

    def matchString(pattern,string):#判断指定字符串是否符合搜索
        nonlocal   searchpattern
        if not searchpattern:searchpattern = transFileMatchToReMatch(pattern)
        return re.fullmatch(searchpattern,string)

    if extnames:
        extnamesList = extnames.split(';')

    files = os.listdir(directory)
    filelist = []
    for file in files:
        if matchString(filenamelike,file):
            if extnames:
                filetype = file.rsplit(".",1)[1]
                if not filetype:continue
                if filetype not in extnamesList:continue
            #print(file)
            filelist.append(file)
    return filelist

# >>> getDirFiles(r"f:\video","7*.*","mp4")
['7.mp4', '7.mp4_blurred.mp4']
# >>> getDirFiles(r"f:\video","7*.*")
['7.mp4', '7.mp4_blurred.mp4']
# >>> getDirFiles(r"f:\video","7*")
['7.mp4', '7.mp4_blurred.mp4', '7月业支会']
# >>> getDirFiles(r"f:\video","7*.*","mp?")
[]
# >>> getDirFiles(r"f:\video","7*.*","mp3")
[]
# >>> getDirFiles(r"f:\video","*.*","mp3")
['audio.mp3']
# >>> getDirFiles(r"f:\video","*.txt")
['test.txt', 'track.txt']
# >>> getDirFiles(r"f:\video","*.*","txt;mp3")
['audio.mp3', 'test.txt', 'track.txt']
# >>>