簡體   English   中英

Regex_search c++

[英]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;
}

為什么它與值4234235不匹配?

在此處測試正則表達式: https://regex101.com/r/A2cg2P/1它確實匹配。

您的在線正則表達式測試是錯誤的,因為您的實際文本是{"|1|":"A","|2|":"B","|37|":"4234235","|4|":"C"} ,您可能會看到您的正則表達式與它不匹配

此外,您在std::regex中使用了 ECMAScript 正則表達式風格,但您的正則表達式符合 PCRE。 例如,ECMAScript 正則表達式不支持\K匹配重置運算符。

您需要一個"\|37\|":"(\d+)正則表達式,請參閱正則表達式演示詳細信息

  • "\|37\|":" - 文字"|37|":"文本
  • (\d+) - 第 1 組:一位或多位數字。

請參閱C++ 演示

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM