gpt4 book ai didi

c++ - Regex_search C++

转载 作者:行者123 更新时间:2023-12-04 17:20:36 26 4
gpt4 key购买 nike

#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"},你可能会看到你的正则表达式 does not match it .

此外,您在 std::regex 中使用了 ECMAScript 正则表达式风格,但您的正则表达式是 PCRE 兼容的。例如。 ECMAScript 正则表达式不支持 \K 匹配重置运算符。

您需要一个 "\|37\|":"(\d+) 正则表达式,请参阅 the regex demo详细信息:

  • "\|37\|":" - 文字 "|37|":" 文本
  • (\d+) - 第 1 组:一个或多个数字。

参见 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;
}

关于c++ - Regex_search C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66413191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com