Boost Spirit:如何计算某些角色的出现次数,然后将结果放入AST
Boost Spirit: how to count occurences of certain characters and then put the result in AST?
我想解析以下文本:
group RGB
group RRGB
group GBBB
group RRGGG
结果AST将是一个表示每个字符计数的结构:
struct group
{
int r;
int g;
int b;
};
对于上面的输入,它将是1,1,1
、2,1,1
、0,1,3
、2,3,0
。
我没有任何语法可以方便地计算字符并强制执行它们的顺序(GBR
应该无法解析)。
https://www.boost.org/doc/libs/develop/libs/spirit/doc/x3/html/spirit_x3/quick_reference/directive.html
有x3::repeat
解析器,但只包含一定数量的字符,它的属性是一个容器。
x3::matches[a]
有bool
属性,但我不知道一个字符会出现多少次
并没有一个解析器可以统计出现次数和返回的匹配次数。我想要像x3::lit("group") >> count['R'] >> count['G'] >> count['B']
这样的语法,但不知道应该如何定义count
。
现在,我能想到的唯一可行的解决方案是x3::lit("group") >> (*x3::char_['R'] >> *x3::char_['G'] >> *x3::char_['B'])[func]
,它调用func
,只对字符串进行操作。IMO这不是一个干净的解决方案,它需要语义操作并创建不必要的字符串。
稍微修改一下"x3/directive/matches.hpp",你就可以得到这样的东西:
#include <boost/spirit/home/x3/core/parser.hpp>
#include <boost/spirit/home/x3/support/traits/move_to.hpp>
#include <boost/spirit/home/x3/support/unused.hpp>
namespace not_boost { namespace not_spirit { namespace not_x3
{
template <typename Subject>
struct count_directive : boost::spirit::x3::unary_parser<Subject, count_directive<Subject>>
{
using base_type = boost::spirit::x3::unary_parser<Subject, count_directive<Subject>>;
static bool const has_attribute = true;
using attribute_type = int;
count_directive(Subject const& subject) : base_type(subject) {}
template <typename Iterator, typename Context
, typename RContext, typename Attribute>
bool parse(Iterator& first, Iterator const& last
, Context const& context, RContext& rcontext, Attribute& attr) const
{
int count=0;
while(this->subject.parse(first, last, context, rcontext, boost::spirit::x3::unused))
{
count++;
}
boost::spirit::x3::traits::move_to(count, attr);
return true;
}
};
struct count_gen
{
template <typename Subject>
count_directive<typename boost::spirit::x3::extension::as_parser<Subject>::value_type>
operator[](Subject const& subject) const
{
return { boost::spirit::x3::as_parser(subject) };
}
};
auto const count = count_gen{};
}}}
在Wandbox 上运行
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 如何克服提升精神AST混乱
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- boost::asio如何生成多个协同程序,然后加入它们
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 在std::thread中,joinable()然后join()线程安全吗
- C++:如何读取分离变量,然后读取向量
- 为什么我的递归函数按降序打印,然后按升序打印?
- 等待整个 omp 块完成,然后再调用第二个函数
- CMake:如何将库 A 链接到库 B,然后将可执行文件链接到库 A
- clang 插件:在编译过程中修改 AST
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- 如何使变量从 x 到 y,然后从 y 返回到 x 并始终重复该过程
- 我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?
- Boost.Spirit将表达转换为AST
- 如何正确地推回然后遍历堆中对象的向量?
- 类继承,ENUM 与 AST 类实现的问题
- Boost Spirit:如何计算某些角色的出现次数,然后将结果放入AST