10.8. fnmatch
--- Unix ファイル名のパターンマッチ¶
ソースコード: Lib/fnmatch.py
このモジュールは Unix のシェル形式のワイルドカードへの対応を提供しますが、(re
モジュールでドキュメント化されている) 正規表現と同じでは ありません 。シェル形式のワイルドカードで使われる特別な文字は:
Pattern | 意味 |
---|---|
* |
すべてにマッチします |
? |
任意の一文字にマッチします |
[seq] |
seq にある任意の文字にマッチします |
[!seq] |
seq にない任意の文字にマッチします |
文字通りにマッチさせる場合はメタ文字を括弧に入れてください。例えば、'[?]'
は文字 '?'
にマッチします。
Note that the filename separator ('/'
on Unix) is not special to this
module. See module glob
for pathname expansion (glob
uses
filter()
to match pathname segments). Similarly, filenames starting with
a period are not special for this module, and are matched by the *
and ?
patterns.
-
fnmatch.
fnmatch
(filename, pattern)¶ Test whether the filename string matches the pattern string, returning
True
orFalse
. Both parameters are case-normalized usingos.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
(filename, pattern)¶ Test whether filename matches pattern, returning
True
orFalse
; the comparison is case-sensitive and does not applyos.path.normcase()
.
-
fnmatch.
filter
(names, pattern)¶ pattern にマッチする names のリストの部分集合を返します。
[n for n in names if fnmatch(n, pattern)]
と同じですが、もっと効率よく実装しています。バージョン 2.2 で追加.
-
fnmatch.
translate
(pattern)¶ シェルスタイルの pattern を、
re.match()
で使用するための正規表現に変換して返します。例:
>>> import fnmatch, re >>> >>> regex = fnmatch.translate('*.txt') >>> regex '.*\\.txt\\Z(?ms)' >>> reobj = re.compile(regex) >>> reobj.match('foobar.txt') <_sre.SRE_Match object at 0x...>
参考
glob
モジュール- Unix シェル形式のパス展開。