// Taken from beautiful code.
#include <stdio.h>
/*
Character Meaning
c Matches any literal character c.
. (period) Matches any single character.
^ Matches the beginning of the input string.
$ Matches the end of the input string.
* Matches zero or more occurrences of the previous character.
*/
#define TRUE 1
#define FALSE 0
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 */
int match(char *regexp, char *text)
{
if (regexp[0] == '^')
return matchhere(regexp+1, 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 */
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))
return matchhere(regexp+1, text+1);
return 0;
}
/* matchstar: search for c*regexp at beginning of text */
int matchstar(int c, char *regexp, char *text)
{
do { /* a * matches zero or more instances */
if (matchhere(regexp, text))
return 1;
} while (*text != '\0' && (*text++ == c || c == '.'));
return 0;
}
void test(char* re, char* string, int expectedReturn) {
printf("Testing re: %s string: %s expectedReturn: %i\n",
re, string, expectedReturn);
int actualReturn = match(re, string);
if(actualReturn == expectedReturn) {
printf("Test suceeded.\n");
} else {
printf("Test failed, returned %i instead!\n",
actualReturn);
}
}
int main() {
test("b*ch", "bitch", FALSE);
test("b.*ch", "bitch", TRUE);
return 0;
}