5

I have a little bit of a problem with a C++11 RegEx and I think it is about greedynes.

Here is a little sample.

#include <stdio.h>
#include <string>
#include <regex>

int main (void)
{
  std::string in="{ab}{cd}[ef]{gh}[ij][kl]";  // the input-string

  std::regex rx1 ("(\\{.+?})(.*)", std::regex::extended);       // non-greedy?
  std::smatch match;

  if (regex_match (in, match, rx1))
  {
    printf ("\n%s\n", match.str(1).c_str());
  }

  return 0;
}

I would expect

{ab} 

for output. But I got

{ab}{cd}[ef]{gh}

I would expect the result I get, if I do it greedy but not with the ? after the .+. Should make it non-greedy, right?

So whats the problem in my idea? Thanks for help!

Chris

chris01
  • 10,921
  • 9
  • 54
  • 93

1 Answers1

5

You need to remove the std::regex::extended, it makes your regex POSIX ERE compliant, and that regex flavor does not support lazy quantifiers.

std::regex rx1("(\\{.+?})(.*)"); 

See the C++ demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563