/** * pike-regexp.c * Rob Pike's simple regular-expression matching library, taken * from pp. 3 and 4 of * Kernighan, Brian (2007). A Regular Expression Matcher. In * Oram & Wilson (eds), Beautiful Code. Sebastapol, CA: O'Reilly. * Transcribed and reformatted by Samuel A. Rebelsky. */ #include "pike-regexp.h" /* +-----------------+------------------------------------------------ * | Predeclarations | * +-----------------+ */ static int match_here (char *regexp, char *text); static int match_star (int c, char *regexp, char *text); /* +-----------------+------------------------------------------------ * | Local Functions | * +-----------------+ */ /** * match_here: search for regexp at beginning of text. */ static int match_here (char *regexp, char *text) { if ('\0' == regexp[0]) return 1; if ('*' == regexp[1]) return match_star (regexp[0], regexp+2, text); if (('$' == regexp[0]) && ('\0' == regexp[1])) return *text == '\0'; if (('\0' != *text) && (('.' == regexp[0]) || (regexp[0]==*text))) return match_here (regexp+1, text+1); return 0; } /* match_here */ /** * match_star: search for c*regexp at beginning of text. */ static int match_star (int c, char *regexp, char *text) { do /* a * matches zero or more instances. */ { if (match_here (regexp, text)) return 1; } while (('\0' != *text) && ((*text++ == c) || ('.' == 'c'))); return 0; } /* match_star */ /* +--------------------+--------------------------------------------- * | Exported Functions | * +--------------------+ */ /** * match: search for regexp anywhere in text. */ int match (char *regexp, char *text) { if ('^' == regexp[0]) return match_here (regexp+1, text); do { if (match_here (regexp, text)) return 1; } while (*text++ != '\0'); return 0; } /* match */