使用Boost Spirit解析文本文件,同时跳过它的大部分
Using Boost Spirit to parse a text file while skipping large parts of it
我有以下std::string
:
<lots of text not including "label A" or "label B">
label A: 34
<lots of text not including "label A" or "label B">
label B: 45
<lots of text not including "label A" or "label B">
...
我想在所有label A
或label B
出现后提取单个整数,并将它们放在相应的vector<int> a, b
中。一种简单但不优雅的方法是使用find("label A")
和find("label B")
,先解析哪个就解析哪个。是否有一种简洁的方式来表达它?如何跳过label A
或label B
之外的所有内容?
你可以直接
omit [ eol >> *char_ - ("nlabel A:") ] >> eol
示例:Live On Coliru
在仓库中也有seek[]
指令。以下代码相当于上面的代码:
repo::seek [ eol >> &lit("int main") ]
下面是解析原始示例的示例:
*repo::seek [ eol >> "label" >> char_("A-Z") >> ':' >> int_ ],
这将解析为std::vector<std::pair<char, int> >
,不需要任何其他内容。
On Coliru Too:
#if 0
<lots of text not including "label A" or "label B">
label A: 34
<lots of text not including "label A" or "label B">
label B: 45
<lots of text not including "label A" or "label B">
...
#endif
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/repository/include/qi_seek.hpp>
#include <fstream>
namespace qi = boost::spirit::qi;
namespace repo = boost::spirit::repository::qi;
int main()
{
std::ifstream ifs("main.cpp");
ifs >> std::noskipws;
boost::spirit::istream_iterator f(ifs), l;
std::vector<std::pair<char, int> > parsed;
using namespace qi;
bool ok = phrase_parse(
f, l,
*repo::seek [ eol >> "label" >> char_("A-Z") >> ':' >> int_ ],
blank,
parsed
);
if (ok)
{
std::cout << "Found:n";
for (auto& p : parsed)
std::cout << "'" << p.first << "' has value " << p.second << "n";
}
else
std::cout << "Fail at: '" << std::string(f,l) << "'n";
}
指出:
seek
确实暴露了匹配的属性,这是非常强大的:repo::seek [ eol >> "label" >> char_("ABCD") >> ':' ]
将"吃掉"标签,但将标签字母(
'A'
,'B'
,'C'
或'D'
)暴露为属性。跳过时的性能可能会非常令人惊讶,请阅读文档中的警告http://www.boost.org/doc/libs/1_55_0/libs/spirit/repository/doc/html/spirit_repository/qi_components/directives/seek.html
Found:
'A' has value 34
'B' has value 45
相关文章:
- Boost Spirit,获取迭代器内部语义动作
- boost::spirit::karma 替代生成器,带有 boost::variant 由字符串和字符串别名组成
- boost::spirit::x3 中的通用解析器生成器
- Boost.Spirit将表达转换为AST
- 使用 Boost.Spirit 解析具有混合数据类型的 OBJ 文件?
- 如何处理Boost Spirit X3导致Visual Studio 2019 "static initialization order fiasco"?
- Boost Spirit X3:将(一些)空格解析为枚举
- Boost Spirit x3 条件(三元)运算符解析器
- 你如何从 Boost Spirit X3 词法解析器中获取字符串?
- 将 Boost.Spirit.X3 解析器拆分为多个 TU
- boost::spirit::x3 中的简单字符串解析器不起作用
- boost::spirit指针属性是用nullptr初始化的吗?
- Boost.Spirit Alternative Parser parallelization
- 如何在 boost::spirit::qi 中将某些语义操作排除在 AST 之外
- 自定义预期失败的完整错误消息(boost::spirit::x3)
- boost::spirit--试图编译大多数简单代码的编译器错误
- Boost.Spirit.Qi 语法,用于 Boost.Fusion 自适应结构中的默认值
- 使用 Boost.Spirit 解析嵌套列表
- (如何)我可以在不安装完整的提升库的情况下使用 boost::spirit X3 吗?
- 使用Boost Spirit解析文本文件,同时跳过它的大部分