【问题标题】:How to extract multiple substrings from a string?如何从一个字符串中提取多个子字符串?
【发布时间】:2021-01-09 01:21:45
【问题描述】:

我的原始字符串看起来像这样<Information name="Identify" id="IdentifyButton" type="button"/>

从这个字符串中,如何提取3个子字符串string name_part = Identify,string id_part="IdentifyButton",type_part="button"

【问题讨论】:

  • 不,实际上我没有一个分隔符,我同意我需要的所有字符串都包含在`" " 但有时我的原始字符串可能包含也可能不包含名称或 ID,所以我需要知道哪个是哪个。
  • 我如何在name="之后获得第一个"?
  • 好吧,也许可以试试分词器:stackoverflow.com/questions/53849/…
  • 另外,迭代字符串,通过检查分隔符的状态机提供字符,以便正确处理字符串中的空格。有了它,您将能够确定要从 XML 复制哪些开始和结束索引以提取部分并推送到字符串向量。请参阅stackoverflow.com/questions/9438209/… 我想您不想只使用tinyxml 为您解析它。

标签: c++ string substring stringstream


【解决方案1】:

假设您不想使用第三方 XML 解析器,您可以简单地为每个名称使用 std::string 的 find():

int main()
{
  std::string s("<Information name = \"Identify\" id = \"IdentifyButton\" type = \"button\" / >");
  std::string names[] = { "name = \"" , "id = \"" , "type = \"" };
  std::string::size_type posStart(0), posEnd(0);
  for (auto& n : names)
  {
    posStart = s.find(n, posEnd) + n.length();
    posEnd = s.find("\"", posStart);
    std::string part = s.substr(posStart, posEnd - posStart);
    std::cout << part << std::endl;
    posEnd++;
  }
}

根据您的容差添加错误检查:)

【讨论】:

    【解决方案2】:

    您可以使用正则表达式来提取由“=”分隔的键值对,中间带有可选的空格字符:

    (\S+?)\s*=\s*([^ />]+)
    

    [^ /&gt;]+ 捕获由除空格、/ 和 > 以外的字符组成的值。这将捕获带或不带引号的值。

    然后使用std::regex_iterator,一个只读的前向迭代器,它将使用正则表达式调用std::regex_search()。这是一个例子:

    #include <string>
    #include <regex>
    #include <iostream>
    
    using namespace std::string_literals;
    
    int main()
    {
        std::string mystring = R"(<Information name="Identify" id="IdentifyButton" type="button" id=1/>)"s;
        std::regex reg(R"((\S+?)\s*=\s*([^ />]+))");
        auto start = std::sregex_iterator(mystring.begin(), mystring.end(), reg);
        auto end = std::sregex_iterator{};
    
        for (std::sregex_iterator it = start; it != end; ++it)
        {
            std::smatch mat = *it;
            auto key = mat[1].str();
            auto value = mat[2].str();
            std::cout << key << "_part=" << value << std::endl;
        }
    }
    

    输出:

    name_part="Identify"
    id_part="IdentifyButton"
    type_part="button"
    id_part=1
    

    这是Demo。至少需要 C++11。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多