问题描述
这是我的语法
unesc_char.add(L"\\a", L'\a')(L"\\b", L'\b')(L"\\f", L'\f')(L"\\n", L'\n')
(L"\\r", L'\r')(L"\\t", L'\t')(L"\\v", L'\v')(L"\\\\", L'\\')
(L"\\\'", L'\'')(L"\\\"", L'\"');
unesc_str = '\"' >> *((boost::spirit::standard_wide::char_ - '\"') | unesc_char) >> '\"';
使用
qi::rule<Iterator, std::wstring()> unesc_str;
qi::symbols<wchar_t const, wchar_t const> unesc_char;
解析失败:"Hello \"->应该返回Hello"
解析正确:"Hello \\"->应该返回Hello \
Parsing fails on : "Hello\"" -> should return Hello"
Parsing correct on : "Hello\\" -> should return Hello\
将规则更改为
unesc_str = '\"' >> *(unesc_char | (boost::spirit::standard_wide::char_ - '\"')) >> '\"';
解析以下内容:"Hello \"->应该返回Hello"
解析失败:"Hello \\"->应该返回Hello \
Parsing correnct on : "Hello\"" -> should return Hello"
Parsing fails on : "Hello\\" -> should return Hello\
如何使两者同时运行?
推荐答案
PEG语法从左到右解析,因此您需要在前面放置 unesc_char
来处理转义.
PEG grammars parse left-to-right, so you need to have unesc_char
in front, to handle escapes.
此外,我认为您可能将自己与输入转义的级别混淆了:
Furthermore I think you're probably confusing yourself with the levels of input escaping:
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
template <typename It>
struct Parser : qi::grammar<It, std::wstring()> {
Parser() : Parser::base_type(unesc_str) {
unesc_char.add
(L"\\a", L'\a')
(L"\\b", L'\b')
(L"\\f", L'\f')
(L"\\n", L'\n')
(L"\\r", L'\r')
(L"\\t", L'\t')
(L"\\v", L'\v')
(L"\\\\", L'\\')
(L"\\'", L'\'')
(L"\\\"", L'\"');
unesc_str = L'"' >> *(unesc_char | ~qi::standard_wide::char_(L'"')) >> L'"';
}
private:
qi::rule<It, std::wstring()> unesc_str;
qi::symbols<wchar_t const, wchar_t const> unesc_char;
};
int main() {
using It = std::wstring::const_iterator;
Parser<It> const p {};
for (std::wstring const input : {
L"\"abaca\\tdabra\"",
LR"("Hello\"")", L"\"Hello\\\"\"", // equivalent
LR"("Hello\\")", L"\"Hello\\\\\"",
}) {
It f = input.begin(), l = input.end();
std::wstring s;
if (parse(f, l, p, s)) {
std::wcout << L"Unescape: " << input << L" -> " << s << L"\n";
}
if (f != l)
std::wcout << "Remaining input: '" << std::wstring(f,l) << "'\n";
}
}
打印
Unescape: "abaca\tdabra" -> abaca dabra
Unescape: "Hello\"" -> Hello"
Unescape: "Hello\"" -> Hello"
Unescape: "Hello\\" -> Hello\
Unescape: "Hello\\" -> Hello\
奖金
如果没有符号
,我可能会变得简单.除非您需要动态的转义符列表,否则它会更灵活并且可能更有效:
BONUS
I'd probably uncomplicate without the symbols
. This is more flexible and probably more efficient unless you need a dynamic list of escapes:
namespace enc = qi::standard_wide;
unesc_str = '"' >> *(
'\\' >> (
'a' >> qi::attr('\a')
| 'b' >> qi::attr('\b')
| 'f' >> qi::attr('\f')
| 'n' >> qi::attr('\n')
| 'r' >> qi::attr('\r')
| 't' >> qi::attr('\t')
| 'v' >> qi::attr('\v')
| enc::char_
) | ~enc::char_('"')) >> '"';
这篇关于提升精神分析报价字符串失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!