2014-02-13 53 views
1

我剛開始學習如何使用regex進行字符串處理(C++11新功能)。如果下面的問題太愚蠢,請原諒我。使用regex_search獲取所有匹配的索引?

目前我採用下面的代碼獲得所有比賽的指數:

string str = "aaabxxxaab"; 
regex rx("ab"); 

vector<int> index_matches; // results saved here (should be {2, 8}) 

int track = 0; 
smatch sm; 
while (regex_search(str, sm, rx)) 
{ 
    index_matches.push_back(track+sm.position()); 

    string tmp = sm.suffix().str(); 
    track += str.length() - tmp.length(); // update base index 

    str = tmp; 
} 

它的工作原理確定,但我每次都手動更新track(基指數),使其正常工作。

與此同時,我注意到已經有smatch::size()smatch::position(),我想結合使用來實現目標。以下是我想將它們組合在一起但不能工作的代碼(即總是隻能得到{2})。

string str = "aaabxxxaab"; 
regex rx("ab"); 

vector<int> index_matches; // results saved here 
          // (should be {2, 8}, but always get only {2}) 

smatch sm; 
regex_search(str, sm, rx); 
for (int i=0; i<sm.size(); i++) 
    index_matches.push_back(sm.position(i)); 

誰能告訴我如何正確使用smatch::size()smatch::position()得到所有匹配的指標?

回答

6

一次執行regex_search只會給您一個匹配項(您查詢的大小和位置)。

您可以:改變你的正則表達式匹配字符串不止一次(然後經過捕獲組迴路),或者只是使用regex_iterator

string str = "aaabxxxaab"; 
regex rx("ab"); 

vector<int> index_matches; // results saved here 
          // (should be {2, 8}, but always get only {2}) 

for(auto it = std::sregex_iterator(str.begin(), str.end(), rx); 
    it != std::sregex_iterator(); 
    ++it) 
{ 
    index_matches.push_back(it->position()); 
} 

在線演示:http://coliru.stacked-crooked.com/a/4d6e1a44b60b7da5

+0

有任何引用/你建議我開始學習'regex'的書嗎? – herohuyongtao

+2

@herohuyongtao [cppreference](http://en.cppreference.com/w/cpp/regex)有一個體面的博覽會,如果你問具體關於C++的'' – Cubbi

+0

謝謝。我會研究它。 – herohuyongtao

相關問題