簡體   English   中英

C ++ boost / regex regex_search

[英]C++ boost/regex regex_search

考慮以下字符串內容:

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. ID 名稱價格的值會有所不同。

我的第一個方法是例如找到價格 ,然后向前移動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;
}

鏈接到實時代碼

由於您嘗試解析的字符串似乎是JSON (JavaScript對象表示法),因此請考慮使用專門的JSON解析器

您可以在http://json.org/上找到多種語言(包括C ++)的JSON解析器的完整列表。 此外,針對此SO問題 ,我發現了一些針對C ++的JSON解析器的優點的討論。

暫無
暫無

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

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