C++多个字符串抓取器(正则表达式)

C++ multiple string grabber(regex)

本文关键字:正则表达式 抓取 字符串 C++      更新时间:2023-10-16

我对 boost::regex 有问题,此解决方案仅适用于每场比赛中的一个结果

boost::regex regex("id="(.*?)""); // should I use this "id="(.*?)"(.*?)<value>(.*?)</value>"?
boost::sregex_token_iterator iter(xml.begin(), xml.end(), regex, 1); // 1 because I just need text inside quotes
boost::sregex_token_iterator end;

现在解析的字符串

<x id="first">
<value>5</value>
</x>
<x id="second"> 
<value>56</value>  
</x>  
etc... 

现在的问题是如何一次解析 id 和值以在匹配循环中同时抓取它们

for( ; iter != end; ++iter ) {
  std::string id(iter->first, iter->second);
  std::string value(?????);
}

Boost.PropertyTree 包含一个 XML 解析器,您可以使用它来代替正则表达式:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
...    
using boost::property_tree::ptree;
ptree pt;
read_xml(istreamOrFilename, pt);
BOOST_FOREACH(ptree::value_type &v, pt) {
    std::string id(v.second.get<std::string>("<xmlattr>.id"));
    std::string value(v.second.get<std::string>("value").data());    
}