- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRegexMatching.py
More file actions
Latest commit
68 lines (60 loc) · 2.07 KB
/
Copy pathRegexMatching.py
File metadata and controls
68 lines (60 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
defisMatch(string, pattern):
"""Determine if the string matches the pattern.
The pattern supports the '.' character, meaning it can match anything, and
the '*' operator, which means zero or more matches of the preceding character.
The function works recursively by splitting off characters from the front
of the string and the pattern as they are matched.
Args:
string: The string we are to match.
pattern: The pattern to subject it to.
Returns:
Boolean true or false for whether the pattern matches the string.
"""
ifnotstring:
# Only both being empty is a match.
returnnotpattern
elifnotpattern:
returnFalse
s0=string[0]
p0=pattern[0]
# Lookahead for '*'
iflen(pattern) >=2andpattern[1] =="*":
# This is a wildcard match.
ifp0=="."ors0==p0:
# The characters match.
# Consider consuming this character in the string but keeping that
# character of the pattern on the matching stack.
ifisMatch(string[1:], pattern):
returnTrue
# Consider consuming the characer and the matching pattern, saying we
# are done recognizing this.
ifisMatch(string[1:], pattern[2:]):
returnTrue
# Either there was no match, or we're considering the hypothesis that
# the wildcard pattern matched zero characters.
returnisMatch(string, pattern[2:])
elifp0=="."ors0==p0:
# It's a match.
returnisMatch(string[1:], pattern[1:])
else:
returnFalse
deftest(tuples):
"""Present the given tuples to the 'isMatch' function for testing.
Prints 'Success' or '*** FAIL ***' for each test case.
Args:
tuples: A list of tuples containing a string, a pattern, and the desired
return of the 'isMatch' function.
"""
fortintuples:
print (t[0], t[1], t[2],
"Success"ifisMatch(t[0], t[1]) ==t[2] else"*** FAIL ***")
test([
("aa", "a", False),
("aa", "aa", True),
("aaa", "a", False),
("aa", "a*", True),
("aa", ".*", True),
("ab", ".*", True),
("aab", "c*a*b", True),
("aa", ".", False),
])