C正则表达式-匹配组

Din*_*lla 2 c regex unix grouping posix

我一直在努力使用C中的正则表达式(只是/usr/include/regex.h)。


我有(假设)数百个正则表达式,其中之一可以匹配输入字符串。目前,我正在这样做(实际上是在生成它):在匹配中进行数百次do-while,如果不匹配则中断并转到另一个。逐一:

do {
    if ( regex_match(str, my_regex1) != MY_REGEX_SUCCESS ) DO_FAIL; //break
    ...
    if ( sscanf(str, " %d.%d.%d.%d / %d ", &___ip1, &___ip2, &___ip3, &___ip4, &___pref) != 5 ) DO_FAIL; //break
    ...
} while (0);

do {
    if ( regex_match(str, my_regex2) != MY_REGEX_SUCCESS ) DO_FAIL; //break
    ...
    ...
} while (0);

do {
    if ( regex_match(str, my_regex3) != MY_REGEX_SUCCESS ) DO_FAIL; //break
    ...
    ...
} while (0);
Run Code Online (Sandbox Code Playgroud)

我想要的是这样的:

const char * match1 = "^([[:space:]]*)([$]([._a-zA-Z0-9-]{0,118})?[._a-zA-Z0-9])([[:space:]]*)$";
const char * match2 = "^([[:space:]]*)(target|origin)([[:space:]]*):([[:space:]]*)([$]([._a-zA-Z0-9-]{0,118})?[._a-zA-Z0-9])([[:space:]]*):([[:space:]]*)\\*([[:space:]]*)$";
const char * match3 = "^([[:space:]]*)(target|origin)([[:space:]]*):([[:space:]]*)([$]([._a-zA-Z0-9-]{0,118})?[._a-zA-Z0-9])([[:space:]]*)/([[:space:]]*)(([0-2]?[0-9])|(3[0-2]))([[:space:]]*):([[:space:]]*)(([1-9][0-9]{0,3})|([1-5][0-9]{4})|(6[0-4][0-9]{3})|(65[0-4][0-9]{2})|(655[0-2][0-9])|(6553[0-5]))([[:space:]]*)$";
char * my_match;
asprintf(&my_match, "(%s)|(%s)|(%s)", match1, match2, match3);


int num_gr = give_me_number_of_regex_group(str, my_match)
switch (num_gr) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

而且不知道该怎么做...

有什么建议么?
谢谢!

Fre*_*Foo 5

我假设你的regex_match是一些组合regcompregexec。要启用分组,您需要调用regcomp带有REG_EXTENDED标志的但不带REG_NOSUB标志的(在第三个参数中)。

regex_t compiled;
regcomp(&compiled, "(match1)|(match2)|(match3)", REG_EXTENDED);
Run Code Online (Sandbox Code Playgroud)

然后为组分配空间。组的数量存储在中compiled.re_nsub。将此号码传递给regexec

size_t ngroups = compiled.re_nsub + 1;
regmatch_t *groups = malloc(ngroups * sizeof(regmatch_t));
regexec(&compiled, str, ngroups, groups, 0);
Run Code Online (Sandbox Code Playgroud)

现在,第一个无效组是在rm_sorm_eo字段中均为-1的组:

size_t nmatched;
for (nmatched = 0; nmatched < ngroups; nmatched++)
    if (groups[nmatched].rm_so == (size_t)(-1))
        break;
Run Code Online (Sandbox Code Playgroud)

nmatched是匹配的带括号的子表达式(组)的数量。添加您自己的错误检查。