4

It is supposed to match "abababab" since "ab" is repeated more than two times consecutively but the code isn't printing any output. Is there some other trick in using regex in C++.

I tried with other languages and it works just fine.

#include<bits/stdc++.h>

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;
}
user2798694
  • 1,023
  • 11
  • 26

1 Answers1

7

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 
Spacemoose
  • 3,856
  • 1
  • 27
  • 48
  • How do I add a flag to return the minimum string that matches for example `aaaaaa` should match `a` repeated 6 times not `aa` repeated three times? – user2798694 Jun 28 '15 at 12:20
  • Hmm. I have to admit you're doing stuff with regex's I haven't tried before. You could try using the "non-greedy-operator" http://stackoverflow.com/questions/11898998/regex-match-non-greedy , which is '?', and see if that gets the results you want. Let me know what you find out! – Spacemoose Jun 28 '15 at 12:30
  • No problem. Regex's can be a pain in the butt, but they are a really worthwhile skill to develop. – Spacemoose Jun 28 '15 at 14:03