gpt4 book ai didi

C++ boost/正则表达式 regex_search

转载 作者:行者123 更新时间:2023-11-28 07:36:22 26 4
gpt4 key购买 nike

考虑以下字符串内容:

string content = "{'name':'Fantastic gloves','description':'Theese gloves will fit any time period.','current':{'trend':'high','price':'47.1000'}";

我从未使用过 regex_search,我一直在寻找使用它的方法 - 我仍然不太明白。从那个随机字符串(它来自 API)我怎么能捕获两件事:

1) 价格 - 在这个例子中是 47.1000

2) 名称 - 在本例中 Fantastic gloves

据我所知,regex_search 是这里最好的方法。我计划将价格用作整数值,我将使用 regex_replace 以便在转换之前从字符串中删除“.”。我只使用过 regex_replace,我发现它很容易使用,我不知道为什么我对 regex_search 这么费劲。

主题演讲:

  1. 内容包含在' '
  2. 内容 id 和值由 分隔:
  3. 内容/值由,分隔
  4. id 的名称价格 的值会有所不同。

我的第一个想法是找到例如 price,然后向前移动 3 个字符 (':') 并收集所有内容,直到下一个 '> - 但是我不确定我是否完全偏离了轨道。

感谢任何帮助。

最佳答案

不需要

boost::regex。正则表达式用于更一般的模式匹配,而您的示例非常具体。处理问题的一种方法是将字符串分解为单独的标记。这是一个使用 boost::tokenizer 的例子:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <map>
int main()
{
std::map<std::string, std::string> m;
std::string content = "{'name':'Fantastic gloves','description':'Theese gloves will fit any time period.','current':{'trend':'high','price':'47.1000'}";
boost::char_separator<char> sep("{},':");
boost::tokenizer<boost::char_separator<char>> tokenizer(content, sep);
std::string id;
for (auto tok = tokenizer.begin(); tok != tokenizer.end(); ++tok)
{
// Since "current" is a special case I added code to handle that
if (*tok != "current")
{
id = *tok++;
m[id] = *tok;
}
else
{
id = *++tok;
m[id] = *++tok; // trend
id = *++tok;
m[id] = *++tok; // price
}
}

std::cout << "Name: " << m["name"] << std::endl;
std::cout << "Price: " << m["price"] << std::endl;
}

Link to live code .

关于C++ boost/正则表达式 regex_search,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16702345/

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