如何在正则表达式中找到所有带有 C 的匹配项?

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

C 的正则表达式库中是否有像 python 中那样的 findall 函数:

re.findall(pattern, input_string)

我有一个包含文件名的字符串,如下所示:

"path/to/file1.ics,path/file2.ics"
,字符串中的文件数量为未确定。我想找到所有文件名(包括它们的路径)并将它们放入字符串数组中。

我正在使用 GNU

regex.h

c regex posix
3个回答
5
投票

假设您使用 POSIX

regcomp
/
regexec
,每次调用
regexec
只会找到字符串中的 first 匹配项。要查找下一个,请使用第一个匹配的结束位置(由
regmatch_t
填充的
regexec
数组的第 0 个条目)作为偏移量,在再次搜索之前应用于该字符串。重复直到没有更多匹配项。如果您愿意,您可以编写一个函数来执行此操作。


3
投票

C 标准库(由 ISO/IEC 9899 指定)不包含正则表达式模块,因此您需要使用外部库。不错的选择包括来自 GNU libcregex.h,详见 /questions/635756PCRE,详见 /questions/1421785


0
投票

如果有人像我一样寻找答案 - 理想的解决方案就在

man regex
的示例中。

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

#define ARRAY_SIZE(arr) (sizeof((arr)) / sizeof((arr)[0]))

static const char *const str =
        "1) John Driverhacker;\n2) John Doe;\n3) John Foo;\n";
static const char *const re = "John.*o";

int main(void)
{
    static const char *s = str;
    regex_t     regex;
    regmatch_t  pmatch[1];
    regoff_t    off, len;

    if (regcomp(&regex, re, REG_NEWLINE))
        exit(EXIT_FAILURE);

    printf("String = \"%s\"\n", str);
    printf("Matches:\n");

    for (int i = 0; ; i++) {
        if (regexec(&regex, s, ARRAY_SIZE(pmatch), pmatch, 0))
            break;

        off = pmatch[0].rm_so + (s - str);
        len = pmatch[0].rm_eo - pmatch[0].rm_so;
        printf("#%d:\n", i);
        printf("offset = %jd; length = %jd\n", (intmax_t) off,
                (intmax_t) len);
        printf("substring = \"%.*s\"\n", len, s + pmatch[0].rm_so);

        s += pmatch[0].rm_eo;
    }

    exit(EXIT_SUCCESS);
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.