我正在使用C语言中的PCRE正则表达式库(http://www.pcre.org/)来解析和匹配我的HTML字符串。为了简化我的问题,假设我有源字符串:"aaa: bbbb:",和我的模式:a(.*?):|b(.*?):,符号?表示它是一个非贪婪匹配,所以答案应该是两个匹配项:一个是"aaa:",另一个是"bbbb:",
我得到了我的结果:
而且得到的结果如下:
这证明了你的答案是相反的:
当找到匹配时,正则表达式的捕获就停止了,所以在尝试匹配后,被捕获,结果的第一行显示整个字符串,#2显示结果偏移与的替代项匹配。
对于,它最终被正则表达式捕获,这解释了两个。
对于,它首先被捕获,因此没有。
然后我编写了以下程序:
char *src = "aaa: bbbb:";
char *pattern = "a(.*?):|b(.*?):";
pcre *re = NULL;
//---missing out---
re = pcre_compile(pattern, // pattern,
0, // options,
&error, // errptr,
&erroffset, // erroffset,
NULL); // tableptr,
while (
(rc = pcre_exec(re, // regex ptr,
NULL, // extra arg,
src, // subject,
strlen(src), // length,
0, // startoffset,
0, // options,
ovector, // ovector,
OVECCOUNT) // ovecsize,
)!=PCRE_ERROR_NOMATCH)
{
printf("\nOK, string has matched ...there are %d matchups\n\n",rc); //
for (i = 0; i < rc; i++)
{
char *substring_start = src + ovector[2*i];
int substring_length = ovector[2*i+1] - ovector[2*i];
printf("$%2d: %.*s length: %d\n", i, substring_length, substring_start,substring_length);
}
src = src + ovector[1]; // to move the src pointer to the end offset of current matchup
if (!src) break;
}
pcre_free(re);
我得到了我的结果:
Source : aaa: bbbb:
Pattern: "a(.*?):|b(.*?):"
OK, string has matched ...there are 2 matches
$ 0: aaa: length: 4
$ 1: aa length: 2
OK, string has matched ...there are 3 matches
$ 0: bbbb: length: 5
$ 1: length: 0
$ 2: bbb length: 3
我在想,我是怎么得到答案"$ 1: length: 0"的?
//----------------------------------------------------------------------------------------
@Jonathan Leffler 我认为你的答案是正确的。
刚刚我尝试了
Source: "aaa: bbb: ccc:"
Pattern: "c(.+?):|a(.+?):|b(.+?):"
而且得到的结果如下:
$ 0: aaa: length: 4
$ 1: length: 0
$ 2: aa length: 2
$ 0: bbbb: length: 5
$ 1: length: 0
$ 2: length: 0
$ 3: bbb length: 3
$ 0: cccc: length: 5
$ 1: ccc length: 3
这证明了你的答案是相反的:
当找到匹配时,正则表达式的捕获就停止了,所以在尝试匹配后,被捕获,结果的第一行显示整个字符串,#2显示结果偏移与的替代项匹配。
对于,它最终被正则表达式捕获,这解释了两个。
对于,它首先被捕获,因此没有。
*
而不是+
。 - jcubic