正则表达式匹配(beautiful code)

来源:互联网 发布:中日进出口贸易数据 编辑:程序博客网 时间:2024/06/08 09:05

/*
 * File:   pregMatch.cpp
 * Author: root
 *
 * 字符                  含义
 *  c             匹配任意的字母c
 *  .(句点)        匹配任意的单个字符
 *  ^             匹配输入字符串的开头
 *  $             匹配输入字符串的结尾
 *  *             匹配前一个字符的零个或者多个出现
 *
 * Created on 2009年9月1日, 上午10:27
 */

#include <stdlib.h>
#include <iostream.h>
/*
 *
 */
int matchhere(char *regexp, char *text);
int matchstar(int c, char *regexp, char *text)
{
    do{
        if(matchhere(regexp, text))
            return 1;
    }while(*text !='/0' && (*text++ ==c) || c=='.');
    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 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 main(int argc, char** argv) {
    char *regexp;
    regexp = new char(15);  
    char *text;
    text = (char *)malloc(sizeof(char)*90);
    cout<<"input regexp:/n";
    cin>>regexp;
    cout<<"input text: /n";
    cin>>text;
    if(match(regexp,text))
        cout<<"find/n";
    else
        cout<<"not in/n";   
    return (EXIT_SUCCESS);
}

若需要识别最左边的以及最长的匹配,那么函数将首先十倍输入字符C的最大重复序列,然后调用matchhere

来尝试把匹配延伸到正则表达式的剩余部分和text的剩余部分:
int matchstar(int c, char *regexp, char *text)
{
    char *t;
    for(t=text;t!='/0' && (*t == c || c == '.'); t++);
    do{
        if(matchhere(regexp, text))
            return 1;
    }while(t-- > text);
    return 0;
}

原创粉丝点击