美文网首页
linux C正则表达式

linux C正则表达式

作者: 一路向后 | 来源:发表于2020-07-17 21:17 被阅读0次

1.程序源码

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

/*取子串的函数*/
static char *substr(const char *str, unsigned int start, unsigned int end)
{
        static char stbuf[256];
        unsigned int n = end - start;

        memcpy(stbuf, str+start, n);

        stbuf[n] = 0x00;

        return stbuf;
}

int main(int argc, char **argv)
{
        regmatch_t pm[10];
        regex_t reg;
        char ebuf[128];
        char lbuf[256];
        char *pattern;
        int x, z, w = 0;
        int cflags =0;
        const size_t nmatch = 10;

        if(argc < 2)
                return -1;

        pattern = argv[1];

        /*编译正则表达式*/
        z = regcomp(&reg, pattern, cflags);
        if(z != 0)
        {
                regerror(z, &reg, pattern, cflags);
                fprintf(stderr, "%s: pattern'%s'\n", ebuf, pattern);
                return -1;
        }

        /*逐行处理输入数据*/
        while(fgets(lbuf, sizeof(lbuf), stdin))
        {
                ++w;

                if((z=strlen(lbuf)) > 0 && lbuf[z-1] == '\n')
                        lbuf[z-1] = 0x00;

                /*对每一行应用正则表达式匹配*/
                z = regexec(&reg, lbuf, nmatch, pm, 0);
                if(z == REG_NOMATCH)
                        continue;
                else if(z != 0)
                {
                        regerror(z, &reg, ebuf, sizeof(ebuf));
                        fprintf(stderr, "%s: regexec('%s')\n", ebuf, lbuf);
                        return -2;
                }

                /*输出处理结果*/
                for(x=0; x<nmatch && pm[x].rm_so != -1; ++x)
                {
                        if(!x)
                                printf("%04d: %s\n", w, lbuf);
                        printf("$%d=%s\n", x, substr(lbuf, pm[x].rm_so, pm[x].rm_eo));
                }
        }

        /*释放正则表达式*/
        regfree(&reg);

        return 0;
}

2.编译源码

$ gcc -o regex regex.c

3.运行程序及其结果

$ ./regex 'regex[a-z]*' < regex.c
0004: #include <regex.h>
$0=regex
0022:   regex_t reg;
$0=regex
0053:       z = regexec(&reg, lbuf, nmatch, pm, 0);
$0=regexec
0059:           fprintf(stderr, "%s: regexec('%s')\n", ebuf, lbuf);
$0=regexec

相关文章

网友评论

      本文标题:linux C正则表达式

      本文链接:https://www.haomeiwen.com/subject/uebnhktx.html