-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathre.c
72 lines (67 loc) · 2.13 KB
/
re.c
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
#include <string.h>
// http://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html
int match(char *regexp, char *text);
int matchhere(char *regexp, char *text);
int matchstar(int c, char *regexp, char *text);
/* match: search for regexp anywhere in text */
/*@
requires ((strlen(regexp)>=0) && \valid(regexp+(0..(strlen(regexp)+1)-1)));
requires ((strlen(text)>=0) && \valid(text+(0..(strlen(text)+1)-1)));
assigns \nothing;
*/
int match(char *regexp, char *text)
{
if (regexp[0] == '^')
return matchhere(regexp+1, text);
/*@
loop invariant ((strlen(regexp)>=0) && \valid(regexp+(0..(strlen(regexp)+1)-1)));
loop invariant ((strlen(text)>=0) && \valid(text+(0..(strlen(text)+1)-1)));
loop assigns text;
loop variant strlen(text);
*/
do { /* must look even if string is empty */
if (matchhere(regexp, text))
return 1;
} while (*text++ != '\0');
return 0;
}
/* matchhere: search for regexp at beginning of text */
/*@
requires ((strlen(regexp)>=0) && \valid(regexp+(0..(strlen(regexp)+1)-1)));
requires ((strlen(text)>=0) && \valid(text+(0..(strlen(text)+1)-1)));
assigns \nothing;
*/
int matchhere(char *regexp, char *text)
{
if (regexp[0] == '\0')
return 1;
if (regexp[1] == '*')
return matchstar(regexp[0], regexp+2, text);
if (regexp[0] == '$' && regexp[1] == '\0')
return *text == '\0';
if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text)) {
//@assert regexp[0]!='\0';
return matchhere(regexp+1, text+1);
}
return 0;
}
/* matchstar: search for c*regexp at beginning of text */
/*@
requires ((strlen(regexp)>=0) && \valid(regexp+(0..(strlen(regexp)+1)-1)));
requires ((strlen(text)>=0) && \valid(text+(0..(strlen(text)+1)-1)));
assigns \nothing;
*/
int matchstar(int c, char *regexp, char *text)
{
/*@
loop invariant ((strlen(regexp)>=0) && \valid(regexp+(0..(strlen(regexp)+1)-1)));
loop invariant ((strlen(text)>=0) && \valid(text+(0..(strlen(text)+1)-1)));
loop assigns text;
loop variant strlen(text);
*/
do { /* a * matches zero or more instances */
if (matchhere(regexp, text))
return 1;
} while (*text != '\0' && (*text++ == c || c == '.'));
return 0;
}