You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Boost::spirit::qi字符串匹配器编译失败问题求助

问题解决:Boost Spirit Qi 单表达式解析带转义的双引号字符串

编译错误原因

你遇到的模板编译错误,本质是规则分支的属性类型不匹配:

  • qi::char_("\\") >> qi::char_ 的属性是 boost::fusion::vector<char, char>(两个字符的融合容器)
  • qi::char_ - '"' 的属性是单个 char
    Spirit 无法自动将这两种不同的属性类型合并到目标 std::string 中,导致模板推导失败。

单表达式解决方案

通过统一分支的属性类型为 std::string,即可用单个表达式完成编译并保留所有匹配字符:

#include <boost/spirit/include/qi.hpp>
#include <string>
#include <iterator>

namespace qi = boost::spirit::qi;

template <typename Iterator>
struct quoted_string_parser : qi::grammar<Iterator, std::string()> {
    quoted_string_parser() : quoted_string_parser::base_type(start) {
        // 单个表达式实现:统一分支属性为std::string
        start = qi::lexeme[
            '"' 
            >> *( 
                qi::raw[qi::char_("\\") >> qi::char_]  // 捕获转义序列为字符串
                | qi::as_string[qi::char_ - '"']       // 捕获普通字符为单字符字符串
            ) 
            >> '"'
        ];
    }
    qi::rule<Iterator, std::string()> start;
};

关键细节

  • qi::raw[...]:将匹配的字符序列直接打包为 std::string,保留转义符和后续字符的原样内容
  • qi::as_string[...]:将单个 char 转换为长度为1的 std::string,确保和前一个分支的属性类型一致
  • qi::lexeme:禁用空白符跳过,保证引号内的所有字符(包括换行)都被原样解析

效果验证

输入 "ab\n\"" 时,解析结果为 ab\n\",完全符合你要求的原样保留转义内容的需求。

内容的提问来源于stack exchange,提问作者Dval

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 02:05:18