喜欢这个问题: https://stackoverflow.com/questions/1421785/how-can-i-use-pcre-to-get-all-match-groups
要获得所有匹配的子字符串,我知道循环方式,但是......如何通过函数pcre_get_substring_list
获取它们?
这是我的代码示例,用于将每个字符串与空格分开:
#include <pcre.h>
#include <stdio.h>
#include <string.h>
int main()
{
pcre* compile;
pcre_extra* extra;;
int res;
int ovector[30];
const char* pattern="\\S+";
const char* errptr;
const char* match[30];
const char** match_list = match;
int erroffset;
char* test_str = "hello world , pcre example!";
compile = pcre_compile(pattern, PCRE_MULTILINE,
&errptr, &erroffset,
NULL);
if ( compile == NULL ) {
fprintf(stderr, "ERROR: Could not compile '%s' : %s\n", pattern, errptr);
exit(1);
}
extra = pcre_study(compile, 0, &errptr);
if ( errptr != NULL ) {
fprintf(stderr, "ERROR: Could not study '%s' : %s\n", pattern, errptr);
exit(1);
}
res = pcre_exec(compile,
extra,
test_str,
strlen(test_str),
0,
0,
ovector,
sizeof(ovector));
if ( res == 0 ) {
res = 30/3;
}
if ( res > 0 ) {
pcre_get_substring_list(test_str, ovector, res, &match_list);
printf("buffer : %s\n", test_str);
printf("match :\n");
for ( int i = 0; match_list[i]; ++ i )
printf("%9s%s\n", " ", match_list[i]);
printf("\n");
if ( match_list )
pcre_free_substring_list(match_list);
}
printf("\n");
if (compile)
pcre_free(compile);
if (extra)
pcre_free(extra);
}
打印:
缓冲区:你好世界,pcre例子!
匹配:你好
预期:
缓冲区:你好世界,pcre例子!
匹配:您好
世界
,
PCRE
例!
感谢您的帮助!