C 正则表达式不匹配

C regex not matched

我正在尝试将此正则表达式 ^%-?\+?#?0?$regexec 相匹配,它在 this site 上运行良好,但可能有问题,因为 regexec 不起作用:

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

int main(void) {
    regex_t regex;
    if (regcomp(&regex, "^%-?\+?#?0?$", 0) != 0) {
        return -1;
    }
    const int match = regexec(&regex, "%-", 0, NULL, REG_EXTENDED);
    if (match == 0) {
        puts("Matched !");
    }
    else {
        puts("Not found !");
    }
    return 0;
}

此示例应显示“匹配”,但显示“未找到”。 问题是否来自我的正则表达式?

在使用 regcomp 编译正则表达式时应设置 REG_EXTENDED 标志,而不是在将其与 regexec 匹配时设置。如果你这样做,它就会起作用,所以:

if (regcomp(&regex, "^%-?\+?#?0?$", REG_EXTENDED) != 0) {
    return -1;
}

const int match = regexec(&regex, "%-", 0, NULL, 0);

(我不知道 POSIX 是否要求标志的具体值,但在我的实现中,编译标志 REG_EXTENDED 与匹配标志 REG_NOTBOL 具有相同的值, 它总是无法匹配字符串的开头 ^.)

如果有人稍后会阅读此页面,则最终代码为:

int main(void) {
    regex_t regex;
    if (regcomp(&regex, "^%-?\+?#?0?$", REG_EXTENDED) != 0) {
        return -1;
    }
    const int match = regexec(&regex, "%-", 0, NULL, 0);
    if (match == 0) {
        puts("Matched !");
    }
    else {
        puts("Not found !");
    }
    return 0;
}

我在编译正则表达式时添加了 REG_EXTENDED 标志,但在执行时将其删除。