Created
February 20, 2017 09:15
-
-
Save dtoma/1a2faeb7315f114024d42a35865fdbf4 to your computer and use it in GitHub Desktop.
book: beautiful code, chapter 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Character | Meaning | |
* c | Matches any literal character c | |
* . | 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 | |
*/ | |
#include <cstdio> | |
int match(char const* regexp, char const* text); | |
int matchhere(char const* regexp, char const* text); | |
int matchstar(char c, char const* regexp, char const* text) ; | |
int match(char const* regexp, char const* text) { | |
if (regexp[0] == '^') { | |
return matchhere(regexp + 1, text); | |
} | |
do { | |
if (matchhere(regexp, text)) { | |
return 1; | |
} | |
} while (*text++ != '\0'); | |
return 0; | |
} | |
int matchhere(char const* regexp, char const* 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; | |
} | |
int matchstar(char c, char const* regexp, char const* text) { | |
do { | |
if (matchhere(regexp, text)) { | |
return 1; | |
} | |
} while (*text != '\0' && (*text++ == c || c == '.')); | |
return 0; | |
} | |
void test(char const* regexp, char const* text) { | |
printf("regexp [%s] %s [%s]\n", regexp, (match(regexp, text) == 1 ? "matches" : "doesn't match"), text); | |
} | |
int main(int ac, char** av) { | |
if (ac == 1) { | |
test("a.c", "abc"); | |
test("a*c", "abc"); | |
return 0; | |
} | |
if (match(av[1], av[2])) { | |
printf("regexp [%s] matches [%s]\n", av[1], av[2]); | |
} else { | |
printf("No match\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment