-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregex.c
More file actions
112 lines (84 loc) · 2.32 KB
/
regex.c
File metadata and controls
112 lines (84 loc) · 2.32 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include "regex.h"
bool match(char *text, char *regex) {
if (*regex == '^')
return matchhere(text, regex + 1);
do {
if (matchhere(text, regex))
return true;
} while (*text++ != '\0');
return false;
}
bool matchhere(char *text, char *regex) {
if (*regex == '\0')
return true;
if (regex[1] == '*')
return matchstar(text, regex + 2, *regex);
if (regex[1] == '+')
return matchplus(text, regex + 2, *regex);
if (*regex == '[') {
int nextSymbolIdx = findIdxOfNxtSymbol(regex);
if (*(regex + 2) == '-' && matchsetrange(text, regex))
return matchhere(text + 1, regex + 5);
else if (matchanychar(text, regex)) {
return matchhere(text + 1, regex + nextSymbolIdx);
}
}
if (*text != '\0' && (*text == *regex
|| *regex == '.'))
return matchhere(text + 1, regex + 1);
return false;
}
bool matchstar(char *text, char *regex, char c) {
do {
if (matchhere(text, regex))
return true;
} while (*text != '\0' && (*text++ == c || c == '.'));
return false;
}
bool matchplus(char *text, char *regex, char c) {
while (*text != '\0' && (*text++ == c)) {
if (matchhere(text, regex))
return true;
}
return false;
}
bool matchanychar(char *text, char *regex) {
size_t strtIdxOfNxtSymbol = findIdxOfNxtSymbol(regex);
if (!strtIdxOfNxtSymbol) {
fprintf(stderr, "Invalid set match expression %s\n", regex);
return false;
}
for (size_t i = 0; i < strtIdxOfNxtSymbol; ++i) {
if (*(regex + i) == *text)
return true;
}
return false;
}
bool matchsetrange(char *text, char *regex) {
int start, end;
start = end = 0;
start = (int) *(regex + 1);
end = (int) *(regex + 3);
if (end == ']') {
fprintf(stderr, "Error set match expression %s\n", regex);
return false;
}
int ti = (int) (*text);
if (ti >= start && ti <= end) {
return true;
}
return false;
}
size_t findIdxOfNxtSymbol(char *regex) {
size_t i;
for (i = 0; ; i++) {
if (regex[i] == '\0')
return 0;
if (regex[i] == ']')
break;
}
return i + 1;
}