C ++ boost / regex regex_search

时间:2013-05-22 22:02:35

标签: c++ boost boost-regex

考虑以下字符串内容:

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)名称 - 在本例中神奇手套

根据我的阅读,regex_search将是最好的方法。我打算将价格用作整数值,我将使用regex_replace在转换之前从字符串中删除“”。我只使用了regex_replace,我发现它很容易使用,我不知道为什么我在regex_search上苦苦挣扎。

注释记号:

  1. 内容包含在''
  2. 内容ID和值由
  3. 分隔
  4. Conent / value由
  5. 分隔
  6. ID的名称价格的值会有所不同。
  7. 我的第一个是找到例如价格然后提前3个字符(':')并收集所有内容直到下一个' - 但是我不确定我是否完全偏离这里。

    感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

不需要

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

答案 1 :(得分:0)

由于您尝试解析的字符串似乎是JSON(JavaScript Object Notation),请考虑使用专门的 JSON解析器

您可以在http://json.org/找到包含C ++在内的多种语言的JSON解析器的完整列表。另外,我发现了一些关于C ++的几个JSON解析器的优点的讨论,以响应这个SO question

相关问题