This regex doesn’t work in c++

Your problem is your backslashes are escaping the ‘1”s in your string. You need to inform std::regex to treat them as ‘\’ ‘s. You can do this by using a raw string R”((.+)\1\1+)”, or by escaping the slashes, as shown here:

#include <regex>
#include <string>
#include <iostream>


int main(){

  std::string s ("xaxababababaxax");
  std::smatch m;
  std::regex e ("(.+)\\1\\1+");

   while (std::regex_search (s,m,e)) {
    for (auto x:m) std::cout << x << " ";
    std::cout << std::endl;
    s = m.suffix().str();
  }

  return 0;
}

Which produces the output

abababab ab 

Leave a Comment