MCPcopy Create free account
hub / github.com/RT-Thread/env-windows / translate

Function translate

tools/python-3.11.9-amd64/Lib/fnmatch.py:74–185  ·  view source on GitHub ↗

Translate a shell PATTERN to a regular expression. There is no way to quote meta-characters.

(pat)

Source from the content-addressed store, hash-verified

72
73
74def 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 ||).

Callers 1

_compile_patternFunction · 0.70

Calls 7

addFunction · 0.70
replaceMethod · 0.45
findMethod · 0.45
appendMethod · 0.45
joinMethod · 0.45
subMethod · 0.45
escapeMethod · 0.45

Tested by

no test coverage detected