Skip to content

Instantly share code, notes, and snippets.

@zqqf16
Created June 6, 2013 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zqqf16/5722281 to your computer and use it in GitHub Desktop.
Save zqqf16/5722281 to your computer and use it in GitHub Desktop.
一个简单的正则表达式匹配器,摘自《代码之美》第一章
int match(char *regexp, char *text)
{
if (regexp[0] == '^')
return matchhere(regexp+1, text);
do {
if (matchhere(regexp, text))
return 1;
} while (*text++ != '\0');
return 0;
}
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;
}
int matchstar(char c, char *regexp, char *text)
{
do {
if (matchhere(regexp, text))
return 1;
} while (*text != '\0' && (*text++ == c || c == '.'));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment