Iterate over regex matches from the last match to the first

Viewed 68

If I'm not missing anything all STL regex iterators fall into forward only category, so i cannot actually iterate regex matches from the last one to back to the first one. Of course i can introduce an extra container like this:

std::string iterateRegexFromEnd(std::string s) {
    std::regex expression("\\w+");
    std::regex_iterator<std::string::iterator> itend;
    std::regex_iterator<std::string::iterator> iterator(s.begin(), s.end(), expression);
    std::vector<std::string> matches;
    while (iterator != itend) {
        matches.push_back(iterator->str());
        ++iterator;
    }

    for (auto matchIterator = matches.rbegin(); matchIterator != matches.rend(); ++matchIterator) {
        if (matchIterator != matches.rbegin()) {
            std::cout << ", ";
        }
        std::cout << *matchIterator;
    }
    std::cout << std::endl;
}

But that looks excessive. Is there any (more or less) elegant way to configure the STL regex algorithm / expression to return matches from the last to first?

0 Answers
Related