3
#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.

3
  • 1
    Attempting to parse JSON-formatted data in C++ using regular expressions will only end in tears. To do this correctly you should use a real JSON parser. Commented Feb 28, 2021 at 19:45
  • Just a side note: Representing regex patterns using raw string literals is way easier,to write and better to read. But @Sam is correct, it's pretty hoeless to get that right. Use a JSON parser library like nlohmann's. Commented Feb 28, 2021 at 19:48
  • 2
    Much like trying to use regex to parse HTML: blog.codinghorror.com/content/images/2014/Apr/… Commented Feb 28, 2021 at 19:49

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.