fnmatch --- Unix ファイル名のパターンマッチ

ソースコード: Lib/fnmatch.py


このモジュールは Unix のシェル形式のワイルドカードに対応しています。これらは、 (re モジュールでドキュメント化されている) 正規表現とは 異なります 。シェル形式のワイルドカードで使われる特殊文字は、次のとおりです。

Pattern

意味

*

すべてにマッチします

?

任意の一文字にマッチします

[seq]

seq にある任意の文字にマッチします

[!seq]

seq にない任意の文字にマッチします

リテラルにマッチさせるには、メタ文字を括弧に入れてください。例えば、'[?]' は文字 '?' にマッチします。

ファイル名の区切り文字 (Unixでは '/') はこのモジュールに固有なものでは ない ことに注意してください。パス名展開については、 glob モジュールを参照してください (glob はパス名の部分にマッチさせるのに filter() を使っています)。同様に、ピリオドで始まるファイル名はこのモジュールに固有ではなくて、 *? のパターンでマッチします。

Also note that functools.lru_cache() with the maxsize of 32768 is used to cache the compiled regex patterns in the following functions: fnmatch(), fnmatchcase(), filter().

fnmatch.fnmatch(name, pat)

Test whether the filename string name matches the pattern string pat, returning True or False. Both parameters are case-normalized using os.path.normcase(). fnmatchcase() can be used to perform a case-sensitive comparison, regardless of whether that's standard for the operating system.

次の例では、カレントディレクトリにある、拡張子が .txt である全てのファイルを表示しています:

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
fnmatch.fnmatchcase(name, pat)

Test whether the filename string name matches the pattern string pat, returning True or False; the comparison is case-sensitive and does not apply os.path.normcase().

fnmatch.filter(names, pat)

Construct a list from those elements of the iterable names that match pattern pat. It is the same as [n for n in names if fnmatch(n, pat)], but implemented more efficiently.

fnmatch.translate(pat)

Return the shell-style pattern pat converted to a regular expression for using with re.match().

例:

>>> 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 シェル形式のパス展開。