一个简单的正则表达式匹配器
发布时间:2020-12-14 01:39:25 所属栏目:百科 来源:网络整理
导读:下面的代码实现如下语法 字符 含义 c 匹配任意的字母c . (句点) 匹配任意的单个字符 ^ 匹配输入字符串的开头 $ 匹配输入字符串的结尾 * 匹配前一个字符的零个或者多个出现 + 匹配前一个字符的1个或多个出现 ? 匹配前一个字符的0个或1个出现 --------------
下面的代码实现如下语法 字符 含义 ----------------------- 对代码之美上面的例子进行简单的扩展,输出是否匹配,并输出匹配串 --------------------- #include <stdio.h> #include <string> bool matchHere(const char *reg,const char *text); bool matchStar(int c,const char *reg,const char *text); bool matchQuestion(int c,const char *text); bool matchPlus(int c,const char *text); using std::string; string matchStr; bool match(const char *reg,const char *text) { matchStr.clear(); //只在起始位置开始匹配 if (reg[0] == '^') { return matchHere(reg + 1,text); } //可以从任意位置开始匹配 while (*text != ' ') { matchStr.clear(); if (matchHere(reg,text) == true) return true; text++; } return false; } bool matchHere(const char *reg,const char *text) { if (*reg == ' ') return true; switch (reg[1]) { case '*': return matchStar(reg[0],reg + 2,text); case '+': return matchPlus(reg[0],text); case '?': return matchQuestion(reg[0],text); } if (reg[0] == '$' && *text == ' ' && reg[1] == ' ') return true; if (*text != ' ' && (*reg == *text || *reg == '.') ) { //向下走一个字符,就把当前字符添加到匹配串中(当后面出现matchHere(...,text + 1)时) matchStr += *text; return matchHere(reg + 1,text + 1); } return false; } bool matchQuestion(int c,const char *text) { //匹配0个出现 if (matchHere(reg,text) == true) return true; //匹配1个出现 if (c == *text) { matchStr += *text; if (matchHere(reg,text + 1) == true) return true; } return false; } bool matchPlus(int c,const char *text) { //匹配1个或多个出现 while (*text == c) { matchStr += *text; if (matchHere(reg,text + 1) == true) return true; text++; } return false; } bool matchStar(int c,const char *text) { do { if (matchHere(reg,text) == true) return true; matchStr += *text; } while (*text != ' ' && *text++ == c); return false; } int main() { char regExp[100],text[300]; while (true) { printf("text: "); gets(text); printf("regExp: "); gets(regExp); printf("%s -- %sn",match(regExp,text) ? "true" : "false",matchStr.c_str()); } } 参考:代码之美 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |