fnmatch
--- Unix 檔名模式匹配¶
原始碼: Lib/fnmatch.py
此模組支援 Unix shell 風格的萬用字元,它與正則表示式(在 re
模組中介紹)並不相同。shell 風格萬用字元所使用的特殊字元如下:
模式 |
含義 |
---|---|
|
匹配所有 |
|
匹配任意單個字元 |
|
匹配 seq 中的任意字元 |
|
匹配不在 seq 中的任意字元 |
對於字面值匹配,請將元字元用方括號括起來。例如,'[?]'
匹配字元 '?'
。
請注意檔名分隔符(在 Unix 上為 '/'
)在此模組中沒有特殊含義。有關路徑名擴充套件,請參見 glob
模組(glob
使用 filter()
來匹配路徑名的各部分)。類似地,以句點開頭的檔名在此模組中也沒有特殊含義,可由 *
和 ?
模式匹配。
除非另有說明,“檔名字串”和“模式字串”指的是 str
或 ISO-8859-1
編碼的 bytes
物件。請注意,下面文件中介紹的函式不允許混合使用 bytes
模式和 str
檔名,反之亦然。
最後,請注意,以下函式中使用 maxsize 為 32768 的 functools.lru_cache()
來快取(已指定型別的)已編譯正則表示式模式:fnmatch()
, fnmatchcase()
, filter()
, filterfalse()
。
- fnmatch.fnmatch(name, pat)¶
測試檔名字串 name 是否匹配模式字串 pat,返回
True
或False
。兩個形參都會使用os.path.normcase()
進行大小寫規範化。fnmatchcase()
可用於執行區分大小寫的比較,無論這對於作業系統是否為標準行為。這個例子將列印當前目錄下所有副檔名為
.txt
的檔名:import fnmatch import os for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): print(file)
- fnmatch.fnmatchcase(name, pat)¶
測試檔名字串 name 是否匹配模式字串 pat,返回
True
或False
;此比較區分大小寫並且不會應用os.path.normcase()
。
- fnmatch.filter(names, pat)¶
根據檔名字串 可迭代物件 names 中能匹配模式字串 pat 的元素,構建一個列表。這等價於
[n for n in names if fnmatch(n, pat)]
,但實現效率更高。
- fnmatch.filterfalse(names, pat)¶
根據檔名字串 可迭代物件 names 中不能匹配模式字串 pat 的元素,構建一個列表。這等價於
[n for n in names if not fnmatch(n, pat)]
,但實現效率更高。在 3.14 版本加入。
- fnmatch.translate(pat)¶
返回 shell 風格的模式 pat 轉換成的正則表示式,用於
re.match()
。該模式應為str
。示例
>>> import fnmatch, re >>> >>> regex = fnmatch.translate('*.txt') >>> regex '(?s:.*\\.txt)\\z' >>> reobj = re.compile(regex) >>> reobj.match('foobar.txt') <re.Match object; span=(0, 10), match='foobar.txt'>
參見
glob
模組Unix shell 風格的路徑擴充套件。