Translate a shell PATTERN to a regular expression. There is no way to quote meta-characters.
(pat)
| 72 | |
| 73 | |
| 74 | def translate(pat): |
| 75 | """Translate a shell PATTERN to a regular expression. |
| 76 | |
| 77 | There is no way to quote meta-characters. |
| 78 | """ |
| 79 | |
| 80 | STAR = object() |
| 81 | res = [] |
| 82 | add = res.append |
| 83 | i, n = 0, len(pat) |
| 84 | while i < n: |
| 85 | c = pat[i] |
| 86 | i = i+1 |
| 87 | if c == '*': |
| 88 | # compress consecutive `*` into one |
| 89 | if (not res) or res[-1] is not STAR: |
| 90 | add(STAR) |
| 91 | elif c == '?': |
| 92 | add('.') |
| 93 | elif c == '[': |
| 94 | j = i |
| 95 | if j < n and pat[j] == '!': |
| 96 | j = j+1 |
| 97 | if j < n and pat[j] == ']': |
| 98 | j = j+1 |
| 99 | while j < n and pat[j] != ']': |
| 100 | j = j+1 |
| 101 | if j >= n: |
| 102 | add('\\[') |
| 103 | else: |
| 104 | stuff = pat[i:j] |
| 105 | if '-' not in stuff: |
| 106 | stuff = stuff.replace('\\', r'\\') |
| 107 | else: |
| 108 | chunks = [] |
| 109 | k = i+2 if pat[i] == '!' else i+1 |
| 110 | while True: |
| 111 | k = pat.find('-', k, j) |
| 112 | if k < 0: |
| 113 | break |
| 114 | chunks.append(pat[i:k]) |
| 115 | i = k+1 |
| 116 | k = k+3 |
| 117 | chunk = pat[i:j] |
| 118 | if chunk: |
| 119 | chunks.append(chunk) |
| 120 | else: |
| 121 | chunks[-1] += '-' |
| 122 | # Remove empty ranges -- invalid in RE. |
| 123 | for k in range(len(chunks)-1, 0, -1): |
| 124 | if chunks[k-1][-1] > chunks[k][0]: |
| 125 | chunks[k-1] = chunks[k-1][:-1] + chunks[k][1:] |
| 126 | del chunks[k] |
| 127 | # Escape backslashes and hyphens for set difference (--). |
| 128 | # Hyphens that create ranges shouldn't be escaped. |
| 129 | stuff = '-'.join(s.replace('\\', r'\\').replace('-', r'\-') |
| 130 | for s in chunks) |
| 131 | # Escape set operations (&&, ~~ and ||). |