Regex with STD::REGEX in C++

Asked

Viewed 270 times

0

I am developing a C++ system that I need to get some information from a String using Regular Expression, I am using a regular expression that I used in PHP perfectly, but in C++ returns blank.

const std::string s = "{{ teste }}";
std::string r = "{{((.)+)}}";

std::regex rgx(r);
std::smatch match;

if (std::regex_search(s.begin(), s.end(), match, rgx)){
    std::cout << "Number of maths: " << match.size() << "\n";
    for(int i=0; i < match.size(); i++){
        std::cout << "match: `" << match[i] << "`\n";
    }
}

In PHP it looked like this and worked perfectly:

$print_value = '/{{((.)+)}}/';
$var_get = "{{ teste }}";
preg_match($print_value, $var_get, $matches, PREG_OFFSET_CAPTURE);
$piece = explode($formatches[0][0], $var_get);
.
.
.

What could possibly be wrong? Other expressions I use work perfectly.
Grateful from now on.

1 answer

1


What is going wrong? PHP, this dynamic language makes everything very simple, and even corrects errors that you might not even notice.

Problem

  • { and } in REGEX is a reserved Character, what PHP must be doing is an automatic cast for literal, because after the { a quantifier is expected 0-9.

PHP must be interpreting its REGEX as /\{\{((.)+)\}\}/ for this reason.

Solution

Change your REGEX in C++ (typical language) to \{\{((.)+)\}\}.

Note

  • Not the need to create (.)+, if your intention is to catch any character, so you are just creating an extra group. Just .+.
  • I made this modification and the result was the same. I generated this regular expression on the site regex101.com and as there worked I thought I had no key problem.

  • 1

    @Pedrosoares I don’t know about C++, so I think you should check if this library doesn’t need to have the bars ( /REGEX/) beginning, end.

  • No ah, because other Regex I made, like this <code>(@for(.*))</code> works without a bar. And with a bar a syntax error is generated.

  • I solved the problem. As I was using double quotes, C++ was considering "" as an escape bar and was not passing to REGEX. I put two bars to be passed and it worked. It was like this: \{\{(.+)\}\}

  • 1

    @Pedrosoares Who good :D , in fact also did not notice this.

  • Thank you so much for your help.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.