c正则表达式regexe

1、标准的C和C++都不支持正则表达式,但有一些函数库可以辅助C/C++程序员完成这一功能,其中最著名的当数Philip Hazel的Perl-Compatible Regular Expression库,许多Linux发行版本都带有这个函数库。
2、C/C++ 中使用正则表达式一般分为三步:
1)编译正则表达式 regcomp()
int regcomp (regex_t *compiled, const char *pattern, int cflags)
这个函数把指定的正则表达式pattern编译成一种特定的数据格式compiled,这样可以使匹配更有效。函数regexec 会使用这个数据在目标文本串中进行模式匹配。执行成功返回0。
2)匹配正则表达式 regexec()
int regexec (regex_t *compiled, char *string, size_t nmatch, regmatch_t matchptr [], int eflags)
当编译好正则表达式后,就可以用regexec 匹配我们的目标文本串了,如果在编译正则表达式的时候没有指定cflags的参数为REG_NEWLINE,则默认情况下是忽略换行符的,也就是把整个文本串当作一个字符串处理。执行成功返回0。
3)释放正则表达式 regfree()
void regfree (regex_t *compiled)
当使用完编译好的正则表达式后,或者要重新编译其他正则表达式的时候,可以用这个函数清空compiled指向的regex_t结构体的内容。请注意,如果是重新编译的话,一定要先清空regex_t结构体。


cflags 有如下4个值或者是它们或运算(|)后的值:
REG_EXTENDED 以功能更加强大的扩展规则表达式的方式进行匹配。
REG_ICASE 匹配字母时忽略大小写。
REG_NOSUB 不用存储匹配后的结果。
REG_NEWLINE 识别换行符,这样'$'就可以从行尾开始匹配,'^'就可以从行的开头开始匹配。

#include <stdio.h>
#include <regex.h>
#include <string.h>

int main() {
    const char *pattern = "reg[a-z]";
    char buf[128], lbuf[128] = "regbkdhkrega";
    int index, cflags = 0;
    regex_t reg;
    regmatch_t pm[3];
    const size_t nmatch = 3;

    if (regcomp(&reg, pattern, cflags)) {
        return 1;
    }

    int size;
    char *s = lbuf;
    printf("%s\n", s);
    while(regexec(&reg, s, nmatch, pm, 0) == 0) {
        for (index = 0; index < nmatch && pm[index].rm_so != -1; index++) {
            printf("(%d, %d)\n", pm[index].rm_so, pm[index].rm_eo);
            size = pm[index].rm_eo - pm[index].rm_so;
            strncpy(buf, s + pm[index].rm_so, size);
            buf[size + 1] = '\0';
            printf("%s\n", buf);
        }
        
        s = s + size; 
    }

    regfree(&reg);
    return 0
}

 

posted @ 2017-10-27 19:22  牧 天  阅读(647)  评论(0)    收藏  举报