forked from subsr97/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathregex-matching.py
64 lines (51 loc) · 1.78 KB
/
regex-matching.py
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
"""
#25
Facebook
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular expression and returns whether or not
the string matches the regular expression.
For example, given the regular expression "ra." and the string "ray", your function should return true.
The same regular expression on the string "raymond" should return false.
Given the regular expression ".*at" and the string "chat", your function should return true.
The same regular expression on the string "chats" should return false.
"""
matched = False
def match(regex, string):
global matched
if regex == "" and string == "":
matched = True
return
elif regex == "" or string == "":
matched = False
return
if len(regex) >= 2 and regex[1] == "*":
front = 0
try:
while string[front] == regex[0] or regex[0] == ".":
match(regex[2:], string[front:])
front += 1
match(regex[2:], string[front:])
except:
pass
else:
if regex[0] == ".":
match(regex[1:], string[1:])
else:
if regex[0] == string[0]:
match(regex[1:], string[1:])
else:
return
def matchRegex(regex, string):
global matched
matched = False
match(regex,string)
return matched
def main():
print(matchRegex("ra.", "ray")) # True
print(matchRegex("ra.", "raymond")) # False
print(matchRegex(".*at", "chat")) # True
print(matchRegex(".*at", "chats")) # False
if __name__ == "__main__":
main()