Teraz, gdy chcę przywrócić wszystkie pozycje meczu w str, takich jak:dlaczego regexec() w posix c zawsze zwraca pierwsze dopasowanie, jak może zwracać wszystkie pozycje meczów tylko raz?
abcd123abcd123abcd
Przypuśćmy, że chcesz dostać wszystko „abcd”, muszę używać regexec(), uzyskać pierwszą pozycję: 0, 3, wtedy użyję:
123abcd123abcd
jako nowy ciąg do ponownego użycia funkcji regexec() i tak dalej. Czytam instrukcję o regexec(), to mówi:
int regexec(const regex_t *preg, const char *string, size_t nmatch,
regmatch_t pmatch[], int eflags);
nmatch and pmatch are used to provide information regarding the location of any
matches.
ale dlaczego nie to działa? To jest mój kod:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
int main(int argc, char **argv)
{
int i = 0;
int res;
int len;
char result[BUFSIZ];
char err_buf[BUFSIZ];
char* src = argv[1];
const char* pattern = "\\<[^,;]+\\>";
regex_t preg;
regmatch_t pmatch[10];
if((res = regcomp(&preg, pattern, REG_EXTENDED)) != 0)
{
regerror(res, &preg, err_buf, BUFSIZ);
printf("regcomp: %s\n", err_buf);
exit(res);
}
res = regexec(&preg, src, 10, pmatch, REG_NOTBOL);
//~ res = regexec(&preg, src, 10, pmatch, 0);
//~ res = regexec(&preg, src, 10, pmatch, REG_NOTEOL);
if(res == REG_NOMATCH)
{
printf("NO match\n");
exit(0);
}
for (i = 0; pmatch[i].rm_so != -1; i++)
{
len = pmatch[i].rm_eo - pmatch[i].rm_so;
memcpy(result, src + pmatch[i].rm_so, len);
result[len] = 0;
printf("num %d: '%s'\n", i, result);
}
regfree(&preg);
return 0;
}
./regex 'hello, world'
wyjście:
num 0: 'hello'
to moje wyjścia szacunku:
num 0: 'hello'
num 1: 'world'
Pokaż nam, jak zadzwonić regexec. –