5,530
社区成员
发帖
与我相关
我的任务
分享
// 字符 含义
// c 匹配任意的字母c
// .(句点)匹配任意的单个字符
// ^ 匹配输入字符串的开头
// $ 匹配输入字符串的结尾
// * 匹配前一个字符的零个或者多个出现
//
/* 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;
}
$ cat f.l ; flex -o f.c f.l ; gcc -O3 f.c -lfl -o f; echo casdn csdn TMMD TAMMD | ./f
%{
%}
%option reject caseless
%%
.*csdn { printf("match rule 1.\n"); REJECT; }
c.*sdn { printf("match rule 2.\n"); REJECT; }
cs.*dn { printf("match rule 3.\n"); REJECT; }
.*TMMD { printf("match rule 4.\n"); REJECT; }
T.*MMD { printf("match rule 5.\n"); REJECT; }
.
%%
match rule 4.
match rule 1.
match rule 2.
match rule 2.
match rule 4.
match rule 1.
match rule 4.
match rule 1.
match rule 4.
match rule 1.
match rule 4.
match rule 1.
match rule 4.
match rule 1.
match rule 4.
match rule 1.
match rule 2.
match rule 3.
match rule 4.
match rule 4.
match rule 4.
match rule 4.
match rule 5.
match rule 4.
match rule 5.
match rule 5.