2015-02-06 113 views
2

我目前在Ubuntu下使用gcc-4.9在C++ 11庫中進行實驗。很明顯,我不明白正則表達式的(默認)ECMAScript語法。C++ 11問題regex_search和ECMAScript語法

我的代碼如下:

#include <iostream> 
#include <exception> 
#include <regex> 

using namespace std; 

int main() { 

string test_str = "this is text containing teeext! Text! Teeeeeeeeeext! This txt should not be matched, nor this Txt"; 
string pattern = "([Tt][e]+xt)"; 

try { 
    regex r(pattern, regex_constants::ECMAScript); 
    smatch results; 

    if (regex_search(test_str, results, r)) 
    { 
     cout << "Found #" << results.size() << " results!" << endl; 
     for(unsigned int i = 0; i < results.size(); i++) 
     { 
       cout << results[i].str() << endl; 
     } 
    } 
    else 
     cout << "no match for " << pattern << endl; 
} catch (regex_error &e) { 
    cout << "what: " << e.what() << "; code: " << e.code() << endl; 
} 
} 

我期望的正則表達式「文本」,「teeext」,「文本」和「Teeeeeeeeeext」原始字符串匹配裏面;但輸出是:

Found #2 results! 
text 
text 

我已經嘗試過多種方式指定正則表達式,如"[T|t]e+xt"和變化,但似乎沒有任何工作。我究竟做錯了什麼?

謝謝你的時間。

+0

國旗是一個錯誤,我只是刪除它^ _ ^; – Alberto 2015-02-06 14:49:35

+0

可能的重複[如何使用新的C++ 0x regex對象在字符串中重複匹配?](http://stackoverflow.com/questions/5586733/how-do-i-use-the-new- C0X正則表達式對象到匹配反覆中之串) – Andreas 2015-02-06 14:54:54

回答

4

你誤解了size()[]match_results對象上的做法。 regex_searchregex_match不應用正則表達式儘可能多次。他們尋找匹配的第一個match_results對象中的子匹配然後對應於正則表達式中的各個組(子括號子表達式),索引0對應於整個匹配。

所以在你的情況下,它停止在第一場比賽(text)。該值由整個正則表達式匹配,並且(由於整個正則表達式是一個捕獲組),也由第一個子組匹配。這就是爲什麼size()2和兩個子匹配返回text