-
Notifications
You must be signed in to change notification settings - Fork 15
/
Regex.py
47 lines (34 loc) · 1.02 KB
/
Regex.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
'''
Writing a simple regex parser (with ".", "*" and "?").
regexMatch("a.*d", "abcd"); // => true
regexMatch("a.d", "abcd"); // => false
regexMatch(".*aow?", "miao"); // => true
'''
def singleMatch(regex, char):
if regex == '.':
return True
return regex == char
def regexMatch(regex, str):
if len(regex) == 0:
if len(str) == 0:
return True
else:
return False
if len(regex) > 1 and regex[1] == '?':
return regexMatch(regex[2:], str) or regexMatch([regex[0]] + regex[2:], str)
if len(regex) > 1 and regex[1] == '*':
# zero
if regexMatch(regex[2:], str):
return True
# multiple
if singleMatch(regex[0], str[0]):
return regexMatch(regex, str[1:])
else:
return False
if singleMatch(regex[0], str[0]):
return regexMatch(regex[1:], str[1:])
else:
return False
print regexMatch("a.*d", "abcd")
print regexMatch("a.d", "abcd")
print regexMatch(".*aow?", "miao")