Guido van Rossum | 762c39e | 1991-01-01 18:11:14 +0000 | [diff] [blame] | 1 | # module 'fnmatch' -- filename matching with shell patterns |
Guido van Rossum | 05e5219 | 1992-01-12 23:29:29 +0000 | [diff] [blame] | 2 | # This version translates the pattern to a regular expression |
| 3 | # and moreover caches the expressions. |
| 4 | |
| 5 | import os |
| 6 | import regex |
| 7 | |
| 8 | cache = {} |
Guido van Rossum | 762c39e | 1991-01-01 18:11:14 +0000 | [diff] [blame] | 9 | |
Guido van Rossum | 762c39e | 1991-01-01 18:11:14 +0000 | [diff] [blame] | 10 | def fnmatch(name, pat): |
Guido van Rossum | 05e5219 | 1992-01-12 23:29:29 +0000 | [diff] [blame] | 11 | name = os.path.normcase(name) |
| 12 | pat = os.path.normcase(pat) |
| 13 | if not cache.has_key(pat): |
| 14 | res = translate(pat) |
| 15 | save_syntax = regex.set_syntax(0) |
| 16 | cache[pat] = regex.compile(res) |
| 17 | save_syntax = regex.set_syntax(save_syntax) |
| 18 | return cache[pat].match(name) == len(name) |
Guido van Rossum | 762c39e | 1991-01-01 18:11:14 +0000 | [diff] [blame] | 19 | |
Guido van Rossum | 05e5219 | 1992-01-12 23:29:29 +0000 | [diff] [blame] | 20 | def translate(pat): |
Guido van Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 21 | i, n = 0, len(pat) |
Guido van Rossum | 05e5219 | 1992-01-12 23:29:29 +0000 | [diff] [blame] | 22 | res = '' |
Guido van Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 23 | while i < n: |
Guido van Rossum | 762c39e | 1991-01-01 18:11:14 +0000 | [diff] [blame] | 24 | c = pat[i] |
Guido van Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 25 | i = i+1 |
Guido van Rossum | 05e5219 | 1992-01-12 23:29:29 +0000 | [diff] [blame] | 26 | if c == '*': |
| 27 | res = res + '.*' |
| 28 | elif c == '?': |
| 29 | res = res + '.' |
| 30 | elif c == '[': |
| 31 | j = i |
| 32 | if j < n and pat[j] == '!': |
| 33 | j = j+1 |
| 34 | if j < n and pat[j] == ']': |
| 35 | j = j+1 |
| 36 | while j < n and pat[j] != ']': |
| 37 | j = j+1 |
| 38 | if j >= n: |
| 39 | res = res + '\\[' |
| 40 | else: |
| 41 | stuff = pat[i:j] |
| 42 | i = j+1 |
| 43 | if stuff[0] == '!': |
| 44 | stuff = '[^' + stuff[1:] + ']' |
| 45 | elif stuff == '^'*len(stuff): |
| 46 | stuff = '\\^' |
| 47 | else: |
| 48 | while stuff[0] == '^': |
| 49 | stuff = stuff[1:] + stuff[0] |
| 50 | stuff = '[' + stuff + ']' |
| 51 | res = res + stuff |
| 52 | elif c in '\\.+^$': |
| 53 | res = res + ('\\' + c) |
| 54 | else: |
| 55 | res = res + c |
Guido van Rossum | 762c39e | 1991-01-01 18:11:14 +0000 | [diff] [blame] | 56 | return res |