我有这个C++程序(实际上它只是一个片段):
#include <iostream>
#include <pcre.h>
#include <string>
using namespace std;
int main(){
string pattern = "<a\\s+href\\s*=\\s*\"([^\"]+)\"",
html = "<html>\n"
"<body>\n"
"<a href=\"example_link_1\"/>\n"
"<a href=\"example_link_2\"/>\n"
"<a href=\"example_link_3\"/>\n"
"</body>\n"
"</html>";
int i, ccount, rc,
*offsets,
eoffset;
const char *error;
pcre *compiled;
compiled = pcre_compile( pattern.c_str(), PCRE_CASELESS | PCRE_MULTILINE, &error, &eoffset, 0 );
if( !compiled ){
cerr << "Error compiling the regexp!!" << endl;
return 0;
}
rc = pcre_fullinfo( compiled, 0, PCRE_INFO_CAPTURECOUNT, &ccount );
offsets = new int[ 3 * (ccount + 1) ];
rc = pcre_exec( compiled, 0, html.c_str(), html.length(), 0, 0, offsets, 3 * (ccount + 1) );
if( rc >= 0 ){
for( i = 1; i < rc; ++i ){
cout << "Match : " << html.substr( offsets[2*i], offsets[2*i+1] - offsets[2*i] ) << endl;
}
}
else{
cout << "Sorry, no matches!" << endl;
}
delete [] offsets;
return 0;
}正如您所看到的,我正在尝试将缓冲区中的html链接与给定的正则表达式(对于C/C++字符串,\\s是\s转义的)进行匹配。但是,即使在缓冲区中有3个链接,并且使用PCRE_CASELESS和PCRE_MULTILINE标志编译regexp,我也只匹配一个元素:
Match : example_link_1注意:我从索引1开始循环,因为pcre库返回匹配的字符串(而不是匹配本身)作为第一个元素,然后是匹配。
这段代码有什么问题?我认为regexp本身是正确的(例如,在PHP中尝试过)。
发布于 2010-04-19 06:18:14
它不应该返回所有的匹配项。试想一下,你请求capturecount,大概是一个或两个(也就是说,要么是整个匹配和一个子表达式,要么只是子表达式,我不记得了,我猜是两个)。您如何期望它知道您从未传递给它的字符串中有多少个匹配项?你不会期望它返回数组中的三个匹配项,对吧?如果你有三千个呢?
自从我处理pcre api以来已经有一段时间了,但我认为您需要再次循环并匹配字符串的其余部分。
https://stackoverflow.com/questions/2664162
复制相似问题