【发布时间】:2011-07-24 20:21:59
【问题描述】:
我正在尝试编写一个简单的程序来查找 HTML 网页中的所有 txt 文件。
我正在使用 C 和 libcurl(为了从 Internet 下载页面)和 PCRE 来扫描页面。
我正在使用下一个模式 - /\w+.txt/g 和下一个代码 -
if(htmlContent == NULL) return;
char pattern[] = "/\\w+.txt/g";
const char *error;
int erroffset, ovector[OVECCOUNT], htmlLength = (int)(sizeof(htmlContent) / sizeof(char));
pcre *re = pcre_compile(pattern,0,&error,&erroffset,NULL);
if (re == NULL) {
printf("PCRE compilation failed at offset %d: %s\n", erroffset, error);
return;
}
int rc = pcre_exec(re,NULL,htmlContent,htmlLength,0,0,ovector,OVECCOUNT);
if(rc < 0) {
pcre_free(re);
return;
}
if (rc == 0)
{
rc = OVECCOUNT/3;
printf("ovector only has room for %d captured substrings\n", rc - 1);
}
int i;
for (i = 0; i < rc; i++)
{
char *substring_start = htmlContent + ovector[2*i];
int substring_length = ovector[2*i+1] - ovector[2*i];
printf("%2d: %.*s\n", i, substring_length, substring_start);
}
运行代码时我得到零结果(顺便说一句,此代码只是来自 curl 回调)
【问题讨论】:
-
我不知道 PCRE API,但我认为您不应该在表达式中使用任何双引号(只有愚蠢的 PHP 会这样做),并且您还想转义点:@ 987654323@
-
Qtax 是对的:当您直接使用 PCRE 库时,您确实不使用正则表达式分隔符(在这种情况下为
/)。 PHP 需要它们,大概是为了使它的正则表达式语法看起来更像 Perl 的,但它在将字符串传递给 PCRE 之前将它们去掉。g修饰符也不需要。 -
使用
sizeof(htmlContent) / sizeof(char)计算的长度可能是错误的。如果htmlContent是一个指针,它只会是4 或8,除以也没什么用。你可能想要strlen(htmlContent)。