Search code examples
c++regexstringiteratorc++17

std::regex_search reverse search


https://stackoverflow.com/a/33307828/9250490 You can find the first 5-sequential-number 12345 via regex_search(s.cbegin(), s.cend()...

string s = "abcde, eee12345 11111ddd 55555 hello";
std::smatch m;
bool b = std::regex_search(s.cbegin(), s.cend(), m, std::regex("[0-9]{5}"));
cout << m[0] << endl;

But if I want to find the last 55555, I tried,

std::regex_search(s.crbegin(), s.crend(), m, std::regex("[0-9]{5}"));

But it doesn't compile with error,

Error C2672 'std::regex_search': no matching overloaded function found ForTest

on Visual Studion 2019 with C++17 standard. Why?


Solution

  • It's because the iterator types do not match, if you look at the source of std::smatch in Visual Studio you'll find this.

    using smatch  = match_results<string::const_iterator>;
    

    And you're trying to pass std::string::const_reverse_iterator in your std::regex_search call.

    Use std::match_results<std::string::const_reverse_iterator> directly instead.

    const std::string s = "abcde, eee12345 11111ddd 55555 hello";
    std::match_results<std::string::const_reverse_iterator> m;
    bool b = std::regex_search(s.crbegin(), s.crend(), m, std::regex("[0-9]{5}"));
    std::cout << m[0] << std::endl;