Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 RegEx, non-greedy

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

like image 482
chris01 Avatar asked Nov 18 '16 10:11

chris01


1 Answers

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

like image 70
Wiktor Stribiżew Avatar answered Sep 30 '22 00:09

Wiktor Stribiżew