正则表达式匹配器------代码之美
重要的、定义明确的、可扩展的基础正则表达式匹配器
#include<iostream>
using namespace std;
//.(句点) 匹配任意的当个字符
//^ 匹配输入字符串的开头
//$ 匹配输入字符串的结尾
//* 匹配前一个字符的零个或者多个出现
/*match: 在text中查找regexp*/
int matchhere(char*regexp, char*text);
int matchstar(int c, char *regexp, char *text);
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;
}
/*matchhere:在text的开头查找regexp*/
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] == '$'&®exp[1] == '\0')
return *text == '\0';
if (*text != '\0' && (regexp[0] == '.' || regexp[0] == *text))
return matchhere(regexp + 1, text + 1);
return 0;
}
/*matchstar:在text的开头查找C*regexp*/
int matchstar(int c, char *regexp, char *text)
{
do { /*通配符 * 匹配零个或多个实例*/
if (matchhere(regexp, text))
return 1;
} while (*text != '\0' && (*text++ == c || c == '.'));
return 0;
}
/*matchstar:搜索c*regexp的出现最左以及最长的匹配*/
int matchstar(int c, char *regexp, char*text,int n=0)
{
char *t;
for (t = text; *t != '\0' && (*t == c || c == '.'); t++)
;
do {/*通配符*匹配零个或者多个实例*/
if (matchhere(regexp, t))
return 1;
} while (t-- > text);
return 0;
}
char a[100], b[100];
int main() {
while (cin >> a >> b)
cout << match(a, b) << endl;
}
浙公网安备 33010602011771号