2010-04-18 28 views
1

我有這個C++程序(實際上它只是一個片段):PCRE多線matche問題

#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轉義)。

Match : example_link_1 

注: 但是,即使在緩衝區中有3個環節,正則表達式與PCRE_CASELESS和PCRE_MULTILINE標誌編譯的,我只有一個元素符合我開始循環來回指數1,因爲PCRE庫返回匹配的字符串(不是匹配本身)作爲第一個元素,然後匹配。

這段代碼有什麼問題?正則表達式本身,我認爲它是正確的(例如在PHP中嘗試)。

回答

2

那麼,它不應該返回所有匹配。試想一下,你要求獲得capturecount,就像一兩個一樣(也就是說,無論是整個比賽還是一個子表達式,或者只是一個子表達式,我都不記得了,我猜兩個)。你如何期望它知道你從未傳過來的字符串中有多少匹配?而且你不希望事情在陣列中返回三場比賽,是嗎?如果你有三千個?

自從我處理pcre api以來已經有一段時間了,但我認爲你需要循環並匹配字符串的其餘部分。

+0

我搜索了這個「循環」並找到了解決方案,謝謝! :) – 2010-04-18 22:22:33

+0

不客氣;-) – 2010-04-18 22:23:40