> (*qi::lexem-6ren">
gpt4 book ai didi

c++ - Boost spirit 将整个比赛作为一个字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:19:20 25 4
gpt4 key购买 nike

我正在尝试使用 boost spirit 框架定义我自己的语法,并且我正在定义这样一个匹配规则:

value = (
char_('"') >>
(*qi::lexeme[
char_('\\') >> char_('\\') |
char_('\\') >> char_('"') |
graph - char_('"') |
char_(' ')
])[some_func] >>
char_('"')
);

我想将一个 Action - some_func - 分配给它的一部分,并将整个匹配字符串作为参数传递。但不幸的是我会得到类似 vector<boost::variant<boost::fusion::vector2 ..a lot of stuff...)...> 的东西.我能否以某种方式将整个数据作为具有大小的 char*、std::string 或什至 void* 获取?

最佳答案

qi::as_string :

演示程序的输出:

DEBUG: 'some\\"quoted\\"string.'
parse success

To be honest, it looks like you are really trying to parse 'verbatim' strings with possible escape chars. In the respect, the use of lexeme seem wrong (the spaces get eaten). If you want to see samples of escaped string parsing, see e.g.

A simple rearrangement that I think could be made, at least might look like:

  value = qi::lexeme [ 
char_('"') >>
qi::as_string [
*(
string("\\\\")
| string("\\\"")
| (graph | ' ') - '"'
)
] [some_func(_1)] >>
char_('"')
];

Note however that you could simply declare the rule without a skipper and drop the lexeme alltogether: http://liveworkspace.org/code/1oEhei$0

代码(实时 liveworkspace )

#include <boost/fusion/adapted.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace qi = boost::spirit::qi;
namespace phx = boost::phoenix;

struct some_func_t
{
template <typename> struct result { typedef void type; };
template <typename T>
void operator()(T const& s) const
{
std::cout << "DEBUG: '" << s << "'\n";
}
};

template <typename It, typename Skipper = qi::space_type>
struct parser : qi::grammar<It, Skipper>
{
parser() : parser::base_type(value)
{
using namespace qi;
// using phx::bind; using phx::ref; using phx::val;

value = (
char_('"') >>
qi::as_string
[
(*qi::lexeme[
char_('\\') >> char_('\\') |
char_('\\') >> char_('"') |
graph - char_('"') |
char_(' ')
])
] [some_func(_1)] >>
char_('"')
);
BOOST_SPIRIT_DEBUG_NODE(value);
}

private:
qi::rule<It, Skipper> value;
phx::function<some_func_t> some_func;
};

bool doParse(const std::string& input)
{
typedef std::string::const_iterator It;
auto f(begin(input)), l(end(input));

parser<It, qi::space_type> p;

try
{
bool ok = qi::phrase_parse(f,l,p,qi::space);
if (ok)
{
std::cout << "parse success\n";
}
else std::cerr << "parse failed: '" << std::string(f,l) << "'\n";

if (f!=l) std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n";
return ok;
} catch(const qi::expectation_failure<It>& e)
{
std::string frag(e.first, e.last);
std::cerr << e.what() << "'" << frag << "'\n";
}

return false;
}

int main()
{
bool ok = doParse("\"some \\\"quoted\\\" string.\"");
return ok? 0 : 255;
}

关于c++ - Boost spirit 将整个比赛作为一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14992295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com