在linux下,如何在C语言中使用正则表达式

来源:互联网 发布:一机一码视频破解知乎 编辑:程序博客网 时间:2024/05/16 04:44
使用POSIX函数库中的Regex系列函数来说明在Linux c下如何使用正则表达式


#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
#include <stdlib.h>
#include <string.h>

#define ERRBUF 128

static char * substr(const char * str, unsigned start, unsigned end);

int main(int argc, char *argv[])
{
        regex_t myreg;
        char err[ERRBUF];
        int resulta,resultb;
        regmatch_t match[4];
        size_t nmatch = 4;

        char pattern[] = "[0-9]{3}";

        resulta = regcomp(&myreg, pattern, REG_EXTENDED | REG_NEWLINE);

        if(resulta != 0)
        {
                fprintf(stderr, "pattern compiled error\n");
                regerror(resulta, &myreg, err, sizeof(err));
                regfree(&myreg);
                exit(1);
        }

        char mystring[] = "192.168.121.112";

        resultb = regexec(&myreg, mystring, nmatch, match, 0);
        if(resultb != 0)
        {
                regerror(resultb, &myreg, err, sizeof(err));
                regfree(&myreg);
                exit(1);
        }

        int x;
        for(x = 0; x < nmatch && match[x].rm_so != -1; x++)
{
                printf("%s\n",substr(mystring, match[x].rm_so, match[x].rm_eo));
}

        printf("x = %d\n",x);
        regfree(&myreg);
        return 0;
}

static char * substr(const char * str, unsigned start, unsigned end)
{
        unsigned n = end - start;
        static char strbuf[256];
        memset(strbuf,'\0',sizeof(strbuf));
        strncpy(strbuf, str + start ,n);
        strbuf[n] = '\0';
        return strbuf;
}


注意:不支持使用 \d 来匹配数字

0 0
原创粉丝点击