Debian Codegraph @

aws_xray_sdk/core/utils/search_pattern.py

raw
1 def wildcard_match(pattern, text, case_insensitive=True):
2 """
3 Performs a case-insensitive wildcard match against two strings.
4 This method works with pseduo-regex chars; specifically ? and * are supported.
5 An asterisk (*) represents any combination of characters.
6 A question mark (?) represents any single character.
7 :param str pattern: the regex-like pattern to be compared against
8 :param str text: the string to compare against the pattern
9 :param boolean case_insensitive: dafault is True
10 return whether the text matches the pattern
11 """
12 if pattern is None or text is None:
13 return False
14
15 pattern_len = len(pattern)
16 text_len = len(text)
17 if pattern_len == 0:
18 return text_len == 0
19
20 # Check the special case of a single * pattern, as it's common
21 if pattern == '*':
22 return True
23
24 if case_insensitive:
25 pattern = pattern.lower()
26 text = text.lower()
27
28 # Infix globs are relatively rare, and the below search is expensive.
29 # Check for infix globs and, in their absence, do the simple thing.
30 if '*' not in pattern or pattern.index('*') == len(pattern) - 1:
31 return _simple_wildcard_match(pattern, text)
32
33 # The res[i] is used to record if there is a match between
34 # the first i chars in text and the first j chars in pattern.
35 # So will return res[textLength+1] in the end
36 # Loop from the beginning of the pattern
37 # case not '*': if text[i]==pattern[j] or pattern[j] is '?',
38 # and res[i] is true, set res[i+1] to true, otherwise false.
39 # case '*': since '*' can match any globing, as long as there is a true
40 # in res before i, all the res[i+1], res[i+2],...,res[textLength]
41 # could be true
42 res = [None] * (text_len + 1)
43 res[0] = True
44 for j in range(0, pattern_len):
45 p = pattern[j]
46 if p != '*':
47 for i in range(text_len - 1, -1, -1):
48 res[i + 1] = res[i] and (p == '?' or (p == text[i]))
49 else:
50 i = 0
51 while i <= text_len and not res[i]:
52 i += 1
53 for m in range(i, text_len + 1):
54 res[m] = True
55
56 res[0] = res[0] and (p == '*')
57
58 return res[text_len]
59
60
61 def _simple_wildcard_match(pattern, text):
62 j = 0
63 pattern_len = len(pattern)
64 text_len = len(text)
65 for i in range(0, pattern_len):
66 p = pattern[i]
67 if p == '*':
68 # Presumption for this method is that globs only occur at end
69 return True
70 elif p == '?':
71 if j == text_len:
72 # No character to match
73 return False
74 j += 1
75 else:
76 if j >= text_len:
77 return False
78
79 if(p != text[j]):
80 return False
81 j += 1
82
83 # Ate up all the pattern and didn't end at a glob, so a match
84 # will have consumed all the text
85 return j == text_len