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.

  • 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](https://stackoverflow.com/questions/36471581/c-c-json-parser/36471724). – Sam Varshavchik Feb 28 '21 at 19:45
  • Just a side note: Representing regex patterns using [raw string literals](https://en.cppreference.com/w/cpp/language/string_literal) 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. – πάντα ῥεῖ Feb 28 '21 at 19:48
  • 2
    Much like trying to use regex to parse HTML: https://blog.codinghorror.com/content/images/2014/Apr/stack-overflow-regex-zalgo.png – Eljay Feb 28 '21 at 19:49

1 Answers1

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;
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563