正则表达式匹配算法

看《代码之美》之美中有个简短而高效的正则表达式匹配算法,这里给一下简单的实现,供学习使用。
#include <iostream>
#include<String>
#include<stdio.h>
using namespace std;

int match(char * regexp, char * text);
int matchhere(char * regexp, char * text);
int matchstar(int c, char *regexp, char * text);

/* match: 在text中查找regexp */
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] == '$' && regexp[0] == '\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;
}

int main()
{
    char * StrSource = "Plastic We use plastic wrap to protect our foods. We put our garbage in plastic bags or plastic cans. We sit on plastic chairs, play with plastic toys, drink from plastic cups, and wash our hair with shampoo from plastic bottles!Plastic does not grow in nature. It is made by mixing certain things together. We call it a produced or manufactured material. Plastic was first made in the 1860s from plants, such as wood and cotton. That plastic was soft and burned easily.";
    char mystr[50];
    while(true){
        scanf("%s",mystr);
        if(match(mystr, StrSource)){
            cout<<"匹配成功!"<<endl;
        }else{
            cout<<"匹配失败!"<<endl;
        }
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值