【发布时间】:2010-04-18 22:03:50
【问题描述】:
我有这个 C++ 程序(实际上它只是一个 sn-p):
#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 标志编译的,我也只匹配一个元素:
Match : example_link_1
注意:我从索引 1 开始循环,因为 pcre 库返回匹配的字符串(不是匹配本身)作为第一个元素,然后是匹配。
这段代码有什么问题?我认为正则表达式本身是正确的(例如在 PHP 中尝试过)。
【问题讨论】: