• regcomp/regexec/regfree--POSIX regex functions


    语法

           #include <sys/types.h>
           #include <regex.h>
    
           int regcomp(regex_t *preg, const char *regex, int cflags);
    
           int regexec(const regex_t *preg, const char *string, size_t nmatch,
                       regmatch_t pmatch[], int eflags);
    
           size_t regerror(int errcode, const regex_t *preg, char *errbuf,
                           size_t errbuf_size);
    
           void regfree(regex_t *preg);

    解析

    正则表达式库函数主要分两部分,正则表达式编译和匹配。编译用于正则表达式提供格式(程序识别),匹配用于提供匹配位置便于提取。

    regcomp()  is  used to compile a regular expression into a form that is suitable for subsequent regexec() searches.
    regexec() is used to match a null-terminated string against the precompiled  pattern  buffer,  preg.   nmatch  and pmatch are used to provide information regarding the location of any matches.  eflags may  be  the bitwise-or  of  one  or  both  of REG_NOTBOL and REG_NOTEOL which cause changes in matching behavior described below.

    示例

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <regex.h>
    
    #define MATCH_NUM 3
    
    char str[]={"Chinese love China! China, fighting!
    "};
    
    int main(int argc, char **argv)
    {
        regex_t reg;
        int ret = 0, i = 0;
        regmatch_t matches[MATCH_NUM];
        char *ps = NULL;
    
        ret = regcomp(&reg, "Chin.", REG_NEWLINE | REG_EXTENDED);
        if(ret != 0){ 
            perror("regcomp");
            exit(1);
        }   
        
        ret = regexec(&reg, str, MATCH_NUM, matches, 0); 
        if(ret != 0){ 
            perror("regexec");
            exit(1);
        }   
        for(i = 0; i < MATCH_NUM; i++){
            ps = strndup(str + matches[i].rm_so, matches[i].rm_eo - matches[i].rm_so);
            if(ps)
                printf("The match %dst is [%s]:[%d:%d]
    ", i, ps, matches[i].rm_so, matches[i].rm_eo);
            free(ps);
        }
    
        regfree(&reg);
    
        return 0;
    }
    ~$gcc regex.c -Wall
    ~$./a.out 
    The match 0st is [Chine]:[0:5]
    The match 1st is []:[-1:-1]
    The match 2st is []:[-1:-1]

    明显不是想要的结果,需继续测试。

  • 相关阅读:
    软件工程课程总结
    团队-象棋游戏-团队一阶段互评
    课后作业-结对编程项目总结
    团队-象棋游戏-模块测试过程
    团队编程项目作业3-模块开发过程
    结对-结对编项目作业名称-最终程序
    2017-10-30 课后作业-阅读任务-阅读提问
    阅读任务-阅读提问
    2017-10-30 课后作业-阅读任务-阅读笔记-2
    2017-10-06-构建之法:现代软件工程-阅读笔记
  • 原文地址:https://www.cnblogs.com/embedded-linux/p/6986631.html
Copyright © 2020-2023  润新知