我正在尝试在一大段文本中查找网址
regex_t reg;
const char *regex="REGEXGOESHERE";
regmatch_t matches[16];
//Read data into variable filecontent
regcomp(®, regex, REG_EXTENDED);
int offset=0;
int j;
int found=0;
int start,end;
while( regexec(®, filecontent+offset, 16, matches, 0) == 0)
{
printf("\n\n");
start = matches[0].rm_so+offset;
end = matches[0].rm_eo-1+offset;
printf("regex /%s/ at bytes %d-%d\n",
regex, start, end);
for (j=start; j<=end; j++)
{
printf("%c",filecontent[j]);
}
offset += matches[0].rm_eo;
found = 1;
}
close(f);
现在,这适用于 const char * regex
中的简单正则表达式,例如 regex = "https?.*.png"
。但是,如果我想要像 (https?:\/\/.*\.(?:png|jpg))
这样的 URL 的复杂正则表达式,我必须转义反斜杠,因此它变成:
"(https?:\\/\\/.*\\.(?:png|jpg))";
然后运行它会出现段错误。
可能出了什么问题?
最佳答案
您需要检查 regcomp 的返回,它会告诉您您的正则表达式无效。
#include <regex.h>
#include <stdio.h>
int main() {
regex_t reg;
const char *regex="(https?:\\/\\/.*\\.(?:png|jpg))";
regmatch_t matches[16];
int ret;
char err[1024];
//Read data into variable filecontent
ret = regcomp(®, regex, REG_EXTENDED);
if (ret != 0) {
regerror(ret, ®, err, 1024);
printf("%s\n", err);
return 1;
}
regfree(®);
return 0;
}
您将得到前面的正则表达式无效
原因是 POSIX 正则表达式(甚至是扩展正则表达式)不支持 (?:
。
关于c - 复杂正则表达式的段错误 - Regex.h,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22567118/