2015-01-13 48 views
1

我正在嘗試使用正則表達式在C++中編寫分割函數。到目前爲止,我已經提出了這個問題。使用C++正則表達式查找第一個匹配的索引

vector<string> split(string s, regex r) 
{ 
    vector<string> splits; 
    while (regex_search(s, r)) 
    { 
     int split_on = // index of regex match 
     splits.push_back(s.substr(0, split_on)); 
     s = s.substr(split_on + 1); 
    } 
    splits.push_back(s); 
    return splits; 
} 

我想知道的是如何填寫註釋行。

回答

4

您只需要多一點,但請參閱以下代碼中的註釋。男人的技巧是使用一個匹配的對象,這裏std::smatch因爲你在std::string匹配,要記住,你匹配(不只是你這樣做):

vector<string> split(string s, regex r) 
{ 
    vector<string> splits; 
    smatch m; // <-- need a match object 

    while (regex_search(s, m, r)) // <-- use it here to get the match 
    { 
    int split_on = m.position(); // <-- use the match position 
    splits.push_back(s.substr(0, split_on)); 
    s = s.substr(split_on + m.length()); // <-- also, skip the whole match 
    } 

    if(!s.empty()) { 
    splits.push_back(s); // and there may be one last token at the end 
    } 

    return splits; 
} 

這可以像這樣使用:

auto v = split("foo1bar2baz345qux", std::regex("[0-9]+")); 

並會給你"foo", "bar", "baz", "qux"

std::smatchstd::match_results的專業化,其參考文件存在here

+0

謝謝,這是完美的作品。我仍然在學習C++,這真的很有幫助。 – Maurdekye

相關問題