Ditched '_find_SET()', since it was a no-value-added wrapper around
[python/dscho.git] / Lib / fnmatch.py
blobed815945e2d9659ba9d1b4524ee8aa5b688f941a
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.)
11 """
13 import re
15 _cache = {}
17 def fnmatch(name, pat):
18 """Test whether FILENAME matches PATTERN.
20 Patterns are Unix shell style:
22 * matches everything
23 ? matches any single character
24 [seq] matches any character in seq
25 [!seq] matches any char not in seq
27 An initial period in FILENAME is not special.
28 Both FILENAME and PATTERN are first case-normalized
29 if the operating system requires it.
30 If you don't want this, use fnmatchcase(FILENAME, PATTERN).
31 """
33 import os
34 name = os.path.normcase(name)
35 pat = os.path.normcase(pat)
36 return fnmatchcase(name, pat)
38 def fnmatchcase(name, pat):
39 """Test wheter FILENAME matches PATTERN, including case.
41 This is a version of fnmatch() which doesn't case-normalize
42 its arguments.
43 """
45 if not _cache.has_key(pat):
46 res = translate(pat)
47 _cache[pat] = re.compile(res)
48 return _cache[pat].match(name) is not None
50 def translate(pat):
51 """Translate a shell PATTERN to a regular expression.
53 There is no way to quote meta-characters.
54 """
56 i, n = 0, len(pat)
57 res = ''
58 while i < n:
59 c = pat[i]
60 i = i+1
61 if c == '*':
62 res = res + '.*'
63 elif c == '?':
64 res = res + '.'
65 elif c == '[':
66 j = i
67 if j < n and pat[j] == '!':
68 j = j+1
69 if j < n and pat[j] == ']':
70 j = j+1
71 while j < n and pat[j] != ']':
72 j = j+1
73 if j >= n:
74 res = res + '\\['
75 else:
76 stuff = pat[i:j]
77 i = j+1
78 if stuff[0] == '!':
79 stuff = '[^' + stuff[1:] + ']'
80 elif stuff == '^'*len(stuff):
81 stuff = '\\^'
82 else:
83 while stuff[0] == '^':
84 stuff = stuff[1:] + stuff[0]
85 stuff = '[' + stuff + ']'
86 res = res + stuff
87 else:
88 res = res + re.escape(c)
89 return res + "$"