Get the index of all matches using regex_search?

前端 未结 1 936
伪装坚强ぢ
伪装坚强ぢ 2021-01-07 06:38

I just start to learn how to use regex for string handling (C++11 new feature). Please pardon me if the following question is too silly.

Cu

相关标签:
1条回答
  • 2021-01-07 07:01

    A single execution of regex_search gives you only one match (whose size and position you queried).

    You could: change your regex to match the substring more than once (and then loop over the capture groups), or just use 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());
    }
    

    online demo: http://coliru.stacked-crooked.com/a/4d6e1a44b60b7da5

    0 讨论(0)
提交回复
热议问题