user14881255
user14881255

Reputation:

Regex_search c++

#include <iostream>
#include <regex>

int main() {

    std::string s = "{\"|1|\":\"A\",\"|2|\":\"B\",\"|37|\":\"4234235\",\"|4|\":\"C\"}";

    std::regex regex("37\\|\\\\\":\\\\\"\\K\\d*");

    std::smatch m;

    regex_search(s, m, regex);
    std::cout << "match: " << m.str(1) << std::endl;

    return 0;
}

Why does it not match the value 4234235?

Testing the regex here: https://regex101.com/r/A2cg2P/1 It does match.

Upvotes: 3

Views: 757

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626826

Your online regex test is wrong because your actual text is {"|1|":"A","|2|":"B","|37|":"4234235","|4|":"C"}, you may see that your regex does not match it.

Besides, you are using an ECMAScript regex flavor in std::regex, but your regex is PCRE compliant. E.g. ECMAScript regex does not support \K match reset operator.

You need a "\|37\|":"(\d+) regex, see the regex demo. Details:

  • "\|37\|":" - literal "|37|":" text
  • (\d+) - Group 1: one or more digits.

See the C++ demo:

#include <iostream>
#include <regex>

int main() {
    std::string s = "{\"|1|\":\"A\",\"|2|\":\"B\",\"|37|\":\"4234235\",\"|4|\":\"C\"}";
    std::cout << s <<"\n";
    std::regex regex(R"(\|37\|":"(\d+))");
    std::smatch m;
    regex_search(s, m, regex);
    std::cout << "match: " << m.str(1) << std::endl;
    return 0;
}

Upvotes: 1

Related Questions