如何使用 boost::spirit::qi 解析行尾?
不应该是一个简单的 eol
能做到这一点吗?
#include <algorithm>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>
using boost::spirit::ascii::space;
using boost::spirit::lit;
using boost::spirit::qi::eol;
using boost::spirit::qi::phrase_parse;
struct fix : std::unary_function<char, void> {
fix(std::string &result) : result(result) {}
void operator() (char c) {
if (c == '\n') result += "\\n";
else if (c == '\r') result += "\\r";
else result += c;
}
std::string &result;
};
template <typename Parser>
void parse(const std::string &s, const Parser &p) {
std::string::const_iterator it = s.begin(), end = s.end();
bool r = phrase_parse(it, end, p, space);
std::string label;
fix f(label);
std::for_each(s.begin(), s.end(), f);
std::cout << '"' << label << "\":\n" << " - ";
if (r && it == end) std::cout << "success!\n";
else std::cout << "parse failed; r=" << r << '\n';
}
int main() {
parse("foo", lit("foo"));
parse("foo\n", lit("foo") >> eol);
parse("foo\r\n", lit("foo") >> eol);
}
输出:
"foo": - success! "foo\n": - parse failed; r=0 "foo\r\n": - parse failed; r=0
为什么后两者失败?
相关问题:
Shouldn't a simple eol
do the trick?
#include <algorithm>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>
using boost::spirit::ascii::space;
using boost::spirit::lit;
using boost::spirit::qi::eol;
using boost::spirit::qi::phrase_parse;
struct fix : std::unary_function<char, void> {
fix(std::string &result) : result(result) {}
void operator() (char c) {
if (c == '\n') result += "\\n";
else if (c == '\r') result += "\\r";
else result += c;
}
std::string &result;
};
template <typename Parser>
void parse(const std::string &s, const Parser &p) {
std::string::const_iterator it = s.begin(), end = s.end();
bool r = phrase_parse(it, end, p, space);
std::string label;
fix f(label);
std::for_each(s.begin(), s.end(), f);
std::cout << '"' << label << "\":\n" << " - ";
if (r && it == end) std::cout << "success!\n";
else std::cout << "parse failed; r=" << r << '\n';
}
int main() {
parse("foo", lit("foo"));
parse("foo\n", lit("foo") >> eol);
parse("foo\r\n", lit("foo") >> eol);
}
Output:
"foo": - success! "foo\n": - parse failed; r=0 "foo\r\n": - parse failed; r=0
Why do the latter two fail?
Related question:
Using boost::spirit, how do I require part of a record to be on its own line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用
space
作为对phrase_parse 的调用的船长。该解析器匹配std::isspace
返回 true 的任何字符(假设您正在进行基于 ascii 的解析)。因此,输入中的\r\n
在被您的eol
解析器看到之前就被您的船长吃掉了。You are using
space
as the skipper for your calls to phrase_parse. This parser matches any character for whichstd::isspace
returns true (assuming you're doing ascii based parsing). For this reason the\r\n
in the input are eaten by your skipper before they can be seen by youreol
parser.