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

问题描述 投票:0回答:1

在学习了一些关于如何在 ANSI C 中使用正则表达式的简单示例和最佳实践之后,我是 C 语言的新手。 我有简单的测试,想要在下面的描述字符串中获取日期 “{d(02/01/2019)}-致电Ms.ha检查此案”。我的意思是想要“02/01/2019” 这是我的代码

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

#define ARRAY_SIZE(arr) (sizeof((arr)) / sizeof((arr)[0]))
// initialize target string and regular expression string

int main(int argc, char **argv)
{
     regex_t preg;

        char *string = "{d(02/01/2019)}-call Ms.ha check this case";
        char *pattern="?[0-9]+(\\/[0-9]+)+(\\/[0-9]+)?"; // I'm stupid pattern in here.
        size_t nmatch = 2;
        regmatch_t pmatch[2];


        regcomp(&preg, pattern, REG_EXTENDED);
        regexec(&preg, string, nmatch, pmatch, 0);

        printf("a matched substring \"%.*s\" is found at position %d to %d.\n",
         pmatch[1].rm_eo - pmatch[1].rm_so, &string[pmatch[1].rm_so],
         pmatch[1].rm_so, pmatch[1].rm_eo - 1);

        regfree(&preg);


        return EXIT_SUCCESS;
}

在这种情况下如何创建图案,

谢谢建议。

c regex
1个回答
0
投票
"[0-9]+(/[0-9]+)+(/[0-9]+)"

您不需要在开头和结尾使用任何分隔符(可能受到 PHP 历史的影响?我不知道有任何其他语言需要在字符串中使用它们)。您也不需要转义斜杠,因为它们在这里没有特殊含义(仅在斜杠为分隔符的语言/结构中需要)。

此外,您想要

pmatch[0]
,而不是
pmatch[1]
。后者只是为您提供第一个捕获组的内容,
/01

您需要检查

regcomp
regexec
的结果;忽视它们就会给你的生活带来错误。在您的情况下,模式开头的
?
正在生成
REG_BADRPT
(重复运算符的无效操作数)。

© www.soinside.com 2019 - 2024. All rights reserved.