2011-03-06 54 views
0

您好,我希望得到以下表達式的值: POLYGON(100 20,30 40,20 10,21 21) 搜索POLYGON(100 20,30 40,20 10 21 21)正則表達式與BoostRegex C++

當我執行下面的代碼我獲得該結果:
POLYGON(100 20,30 40,20 10,21 21)
結果= 100 20
R2 = 100個
R2 = 20個
R2 =,21 21
r2 = 21
大小= 7

我不知道爲什麼我沒有獲得middled值...

感謝您的幫助

#include <iostream> 
#include <boost/regex.hpp> 

using namespace std; 

void testMatch(const boost::regex &ex, const string st) { 
cout << "Matching " << st << endl; 
if (boost::regex_match(st, ex)) { 
    cout << " matches" << endl; 
} 
else { 
    cout << " doesn’t match" << endl; 
} 
} 

void testSearch(const boost::regex &ex, const string st) { 
cout << "Searching " << st << endl; 
string::const_iterator start, end; 
start = st.begin(); 
end = st.end(); 
boost::match_results<std::string::const_iterator> what; 
boost::match_flag_type flags = boost::match_default; 
while(boost::regex_search(start, end, what, ex, flags)) 
{ 
    cout << " " << what.str() << endl; 
    cout << " result = " << what[1] << endl; 
    cout << " r2 = " << what[2] << endl; 
cout << " r2 = " << what[3] << endl; 
cout << " r2 = " << what[4] << endl; 
cout << " r2 = " << what[5] << endl; 
cout << "size = " << what.size() << endl; 
    start = what[0].second; 
} 
} 

int main(int argc, char *argv[]) 
{ 
static const boost::regex ex("POLYGON\\(((\\-?\\d+) (\\-?\\d+))(\\, (\\-?\\d+) (\\-?\\d+))*\\)"); 
testSearch(ex, "POLYGON(1 2)"); 
testSearch(ex, "POLYGON(-1 2, 3 4)"); 
testSearch(ex, "POLYGON(100 20, 30 40, 20 10, 21 21)"); 
return 0; 
} 

回答

0

我得到了IRC頻道的結果。 正則表達式是:

static const boost::regex ex("[\\d\\s]+"); 
static const boost::regex ex("[\\-\\d\\s]+"); 
2

我不是一個正則表達式的專家,但我讀了你的常規表達和它似乎是正確的。

This forum post似乎在談論完全相同的事情,其中​​Boost.Regex只返回正則表達式的最後結果。顯然,默認情況下,Boost只會跟蹤重複比賽的最後一場比賽。但是,有一個實驗性功能可以讓您改變這一點。 More info here,在「重複捕獲」下。

還有其他2「解決方案」,但:

  1. 使用正則表達式來跟蹤第一對數字,然後得到與對刪除的子做對串另一個正則表達式,直到你」我得到了所有的輸入。使用Boost.Spirit,它可能比Boost.Regex更適合解析輸入。