我使用C中的PCRE正则表达式库(http://www.pcre.org/)来解析和匹配我的HTML字符串。为了简化我的问题,假设我得到了源字符串:“AAA:BBBB:”,我的模式:一个(*):| B:,符号(*?)?表明它是一个非贪婪匹配,所以答案应该是两个对决:一个是“AAA:”和其他“BBBB:”,使用PCRE的奇怪答案正则表达式
然后我编程:
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:长度:0”?
// -------------------------------------------- --------------------------------------------
@Jonathan勒夫勒我认为你的回答是正确的。
刚才我试着
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
这证明你的答案相反:
正则表达式的捕获时停止对决被发现,所以aaa:
与a(.+?):
被捕获后尝试匹配c(.+?):
,并且结果的第一行显示整个字符串时,#2示出结果失调匹配了替代c(.+?):
对于b(。+?),它被认为是最后的正则表达式所捕获,即说明了这两种length : 0
对于C(。+? ),它首先被捕获,所以没有length : 0
你能否扩充示例源代码以便编译? – thuovila 2013-03-06 11:46:38
也许是因为你使用'*'而不是'+' – jcubic 2013-03-06 11:48:42