Get the index of all matches using regex_search?
c++, c++11, regex, string
Solution
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
Problem
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. Currently I apply the following code to get the index of all matches: ``` 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; } ``` It works OK, but I have to update `track` (base index) manually each time to make it work correctly. At the same time, I noticed that there are already `smatch::size()` and `smatch::position()`, which I want to combine using to achieve the goal. The following is the code I want to combine them together but cannot work (i.e. always get only `{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)); ``` Can someone tell me how to correctly use `smatch::size()` and `smatch::position()` to get all matched indexes?