]> gitweb.ps.run Git - onefile/blob - regex.c
add regex.c
[onefile] / regex.c
1 int match(char r, char t)
2 {
3     return r == '.' || r == t;
4 }
5 int matchstr(const char *r, const char *t)
6 {
7     int state = 0, i = (r[0] == '^' ? 1 : 0), j = 0;
8     while (1)
9     {
10         if (r[i] == '\0')
11             return 1;
12         if (r[i] == '$' && r[i + 1] == '\0')
13             return t[j] == '\0';
14         if (t[j] == '\0')
15             return 0;
16
17         if (state == 0) // base case
18         {
19             if (r[i + 1] == '*')
20                 state = 1;
21             else if (match(r[i], t[j]))
22                 i++, j++;
23             else if (r[0] == '^')
24                 return 0;
25             else
26                 i = 0;
27         }
28         if (state == 1) // star
29         {
30             if (!match(r[i], t[j]) || match(r[i + 2], t[j]))
31                 state = 0, i += 2;
32             else
33                 j++;
34         }
35     }
36     return 0;
37 }
38
39 #include <stdio.h>
40
41 int main(int argc, char **argv)
42 {
43     if (argc != 3)
44     {
45         printf("Usage: %s <regex> <text>\n", argv[0]);
46         return 2;
47     }
48     return !matchstr(argv[1], argv[2]);
49 }