You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中用正则解析格式异常的JSON字符串报错求助

问题:提取JSON响应中{}内的内容到vector

我的应用从服务器接收JSON响应,但该响应有时格式存在问题,因此我希望将其作为字符串解析。示例响应如下:

[{
"Id": "0000001",
"fName": "ABCD",
"lName": "ZY",
"salary": 1000
},
{
"Id": "0000002",
"fName": "EFGH",
"lName": "XW",
"salary": 1010
},
{
"Id": "0000003",
"fName": "IJKL",
"lName": "VU",
"salary": 1020
}]

我希望将每个大括号{}之间的内容提取出来,存入多个vector中以便轻松迭代解析数据。我尝试使用str.substr(first, last - first),但仅能得到单个字符串,无法获取所有匹配结果。之后尝试使用正则表达式代码,却抛出regex_error(error_badrepeat): One of *?+{ was not preceded by a valid regular expression异常,代码如下:

std::regex _regex("{", "}");
std::smatch match;
while (std::regex_search(GetScanReportURL_Res, match, _regex))
{
    std::cout << match.str(0);
}
解决方案

1. 修正正则表达式错误

你写的std::regex _regex("{", "}");是错误的构造方式,std::regex的构造函数不接受两个独立字符串参数。同时,{}在正则表达式中属于特殊字符(用于表示重复次数),必须转义才能匹配字面量。

正确的正则表达式可以用原始字符串字面量来避免转义麻烦,匹配{}及其内部内容:

std::regex _regex(R"(\{([^}]+)\})");
  • \{:匹配字面量左大括号
  • ([^}]+):捕获组,匹配任意非右大括号的字符(至少一个),对应{}之间的内容
  • \}:匹配字面量右大括号

2. 提取所有匹配内容到vector

修改代码,将每个捕获到的内容存入std::vector<std::string>:

#include <regex>
#include <string>
#include <vector>
#include <iostream>

int main() {
    std::string GetScanReportURL_Res = R"([{
"Id": "0000001",
"fName": "ABCD",
"lName": "ZY",
"salary": 1000
},
{
"Id": "0000002",
"fName": "EFGH",
"lName": "XW",
"salary": 1010
},
{
"Id": "0000003",
"fName": "IJKL",
"lName": "VU",
"salary": 1020
}])";

    std::regex _regex(R"(\{([^}]+)\})");
    std::smatch match;
    std::vector<std::string> results;

    std::string temp_str = GetScanReportURL_Res;
    while (std::regex_search(temp_str, match, _regex)) {
        // match[1]对应捕获组的内容(去掉{}的部分),match[0]是带{}的完整匹配
        results.push_back(match[1].str());
        temp_str = match.suffix().str(); // 更新字符串为匹配后的剩余部分
    }

    // 测试输出
    for (const auto& item : results) {
        std::cout << "提取内容:\n" << item << "\n-----------------\n";
    }

    return 0;
}

3. 额外建议

如果你的JSON响应可能存在嵌套{}(比如某个字段值是嵌套JSON对象),上述简单正则会失效。这种情况下,建议使用容错性强的JSON解析库(例如nlohmann/json),这类库能处理大部分格式不严谨的JSON,比手动写正则更可靠。

内容的提问来源于stack exchange,提问作者Nani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 04:36:23