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

标签 c++ regex string boost boost-regex

我对 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 和 value 以在 matches 循环中同时获取它们

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());    
}

关于C++ 多字符串抓取器(正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10166549/

相关文章:

javascript - 正则表达式获取两个字符串之间的字符串

c++ - 在 C++ 中连接不同类型的字符串

c++ - 将csv字符串读入 vector C++

Python从字符串中删除特定的零

c++ - PROCESS_MEMORY_COUNTERS 结构中的哪个成员给出了当前使用的内存

c++ - 为什么动态绑定(bind)可以覆盖 C++ 中的名称隐藏?

c++ - 为什么在gtkmm中使用CellRenderer时TreeView中的信息显示两次

c++ - 在参数列表中使用表达式的意外输出

javascript - 正则表达式 - indexof - 拆分和替换 我应该如何正确应用它们?

javascript - 替换为 javascript 中的 regExp