1 """Filename matching with shell patterns.
3 fnmatch(FILENAME, PATTERN) matches according to the local convention.
4 fnmatchcase(FILENAME, PATTERN) always takes case in account.
6 The functions operate by translating the pattern into a regular
7 expression. They cache the compiled regular expressions for speed.
9 The function translate(PATTERN) returns a regular expression
10 corresponding to PATTERN. (It does not compile it.)
15 def fnmatch(name
, pat
):
16 """Test whether FILENAME matches PATTERN.
18 Patterns are Unix shell style:
21 ? matches any single character
22 [seq] matches any character in seq
23 [!seq] matches any char not in seq
25 An initial period in FILENAME is not special.
26 Both FILENAME and PATTERN are first case-normalized
27 if the operating system requires it.
28 If you don't want this, use fnmatchcase(FILENAME, PATTERN).
32 name
= os
.path
.normcase(name
)
33 pat
= os
.path
.normcase(pat
)
34 return fnmatchcase(name
, pat
)
36 def fnmatchcase(name
, pat
):
37 """Test wheter FILENAME matches PATTERN, including case.
39 This is a version of fnmatch() which doesn't case-normalize
43 if not _cache
.has_key(pat
):
46 save_syntax
= regex
.set_syntax(0)
47 _cache
[pat
] = regex
.compile(res
)
48 save_syntax
= regex
.set_syntax(save_syntax
)
49 return _cache
[pat
].match(name
) == len(name
)
52 """Translate a shell PATTERN to a regular expression.
54 There is no way to quote meta-characters.
68 if j
< n
and pat
[j
] == '!':
70 if j
< n
and pat
[j
] == ']':
72 while j
< n
and pat
[j
] != ']':
80 stuff
= '[^' + stuff
[1:] + ']'
81 elif stuff
== '^'*len(stuff
):
84 while stuff
[0] == '^':
85 stuff
= stuff
[1:] + stuff
[0]
86 stuff
= '[' + stuff
+ ']'
89 res
= res
+ ('\\' + c
)