chris chris - 1 year ago 164
C++ Question

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


for output.
But I got


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!


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download