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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With