|
1 | | -# module 'fnmatch' -- filename matching with shell patterns |
2 | | -# This version translates the pattern to a regular expression |
3 | | -# and moreover caches the expressions. |
| 1 | +"""Filename matching with shell patterns. |
4 | 2 |
|
5 | | -import os |
6 | | -import regex |
| 3 | +fnmatch(FILENAME, PATTERN) matches according to the local convention. |
| 4 | +fnmatchcase(FILENAME, PATTERN) always takes case in account. |
7 | 5 |
|
8 | | -cache = {} |
| 6 | +The functions operate by translating the pattern into a regular |
| 7 | +expression. They cache the compiled regular expressions for speed. |
| 8 | +
|
| 9 | +The function translate(PATTERN) returns a regular expression |
| 10 | +corresponding to PATTERN. (It does not compile it.) |
| 11 | +""" |
| 12 | + |
| 13 | +_cache = {} |
9 | 14 |
|
10 | 15 | def fnmatch(name, pat): |
| 16 | + """Test whether FILENAME matches PATTERN. |
| 17 | + |
| 18 | + Patterns are Unix shell style: |
| 19 | + |
| 20 | + * matches everything |
| 21 | + ? matches any single character |
| 22 | + [seq] matches any character in seq |
| 23 | + [!seq] matches any char not in seq |
| 24 | + |
| 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). |
| 29 | + """ |
| 30 | + |
| 31 | + import os |
11 | 32 | name = os.path.normcase(name) |
12 | 33 | pat = os.path.normcase(pat) |
13 | | - if not cache.has_key(pat): |
| 34 | + return fnmatchcase(name, pat) |
| 35 | + |
| 36 | +def fnmatchcase(name, pat): |
| 37 | + """Test wheter FILENAME matches PATTERN, including case. |
| 38 | + |
| 39 | + This is a version of fnmatch() which doesn't case-normalize |
| 40 | + its arguments. |
| 41 | + """ |
| 42 | + |
| 43 | + if not _cache.has_key(pat): |
14 | 44 | res = translate(pat) |
| 45 | + import regex |
15 | 46 | save_syntax = regex.set_syntax(0) |
16 | | - cache[pat] = regex.compile(res) |
| 47 | + _cache[pat] = regex.compile(res) |
17 | 48 | save_syntax = regex.set_syntax(save_syntax) |
18 | | - return cache[pat].match(name) == len(name) |
| 49 | + return _cache[pat].match(name) == len(name) |
19 | 50 |
|
20 | 51 | def translate(pat): |
| 52 | + """Translate a shell PATTERN to a regular expression. |
| 53 | + |
| 54 | + There is no way to quote meta-characters. |
| 55 | + """ |
| 56 | + |
21 | 57 | i, n = 0, len(pat) |
22 | 58 | res = '' |
23 | 59 | while i < n: |
|
0 commit comments