参考资料:

  • https://blog.csdn.net/liangkwok/article/details/6562121

  • http://c.biancheng.net/cpp/html/1428.html

  • GNU Regex Library 库接口

#include<stdio.h>

#include<sys/types.h>
#include<regex.h>

int main(int argc, char * argv[])
{
    int i, status;

    if(argc == 1)
    {
        printf("no param...\n");
        return 0;
    }

    // 日期 YYYY/MM/DD
    const char * pattern = "^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$";
    regex_t preg;
    size_t nmatch = 1;
    regmatch_t pmatch[1];

    regcomp(&preg, pattern, REG_EXTENDED);
    status = regexec(&preg, argv[1], nmatch, pmatch, 0);
    if(REG_NOMATCH == status)
    {
        printf("match fail...\n");
        return 0;
    }

    for (i = pmatch[0].rm_so; i < pmatch[0].rm_eo; ++i)
    {
        putchar(argv[1][i]);
    }
    putchar('\n');
    
    regfree(&preg);
    return 0;
}

运行结果

  • PCRE(Perl Compatible Regular Expressions)库接口
#include<stdio.h>
#include<string.h>

#include<sys/types.h>
#include<regex.h>

#include<pcre.h>

int main(int argc, char * argv[])
{
    // int i, status;

    if(argc == 1)
    {
        printf("no param...\n");
        return 0;
    }

    // 日期 YYYY/MM/DD
    const char * pattern = "^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$";
    
    const char * pText = argv[1];
    const char * pErrMsg = NULL;
    pcre * pPcre = NULL;
    int nOffset = -1;
    
    if (NULL == (pPcre = pcre_compile(pattern, 0, &pErrMsg, &nOffset, NULL)))
    {
        printf("ErrMsg=%s, Offset=%d/n", pErrMsg, nOffset);
        return 1;
    }
    int status = pcre_exec(pPcre, NULL, pText, strlen(pText), 0, 0, NULL, 0);
    if(status <= 0)
    {
        printf("match error...\n");
        free(pPcre);
        return 1;
    }
    free(pPcre);
    return 0;
}

版权声明:本文为jerryhanjj原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/jerryhanjj/article/details/118671532