![](/img/trans.png)
[英]How to extract multiple structures from a string with boost::spirit
[英]Boost Spirit - Extract list into single string
我在准确了解Spirit决定如何以及何时将匹配项合并到单个实体中时遇到了麻烦。 我想要做的是匹配双方括号内的单词列表,我想提取括号内的全文。 例:
[[This is some single-spaced text]] -> "This is some single-spaced text"
我的语法如下:
qi::rule<Iterator, std::string()> word = +(char_ - char_(" []"));
qi::rule<Iterator, std::string()> entry = lit("[[") >> word >> *(char_(' ') >> word) >> lit("]]") >> -qi::eol;
std::string text;
bool r = parse( first, last, entry, text );
但是,这将示例文本解析如下:
[[This is some single-spaced text]] -> "Thisissomesingle-spacedtext"
我不明白为什么会这样。 如果我正确理解Spirit的话,我不会在这里使用lit
,也不会有任何规则或解析器会忽略空格。 我不确定如何验证语法结果是否是我想要的结果(例如,避免在每个单词的元组中都有空格,而不是将其串联)。
我应该怎么做才能获得想要的结果?
您可能正在使用(字符串)流。 在这种情况下,您将需要在流上设置std::noskipws
:
#include <boost/spirit/include/qi.hpp>
#include <sstream>
namespace qi = boost::spirit::qi;
int main()
{
typedef boost::spirit::istream_iterator Iterator;
std::istringstream iss("[[This is some single-spaced text]]");
qi::rule<Iterator, std::string()> entry = "[[" >> qi::lexeme [ +(qi::char_ - "]]") ] >> "]]";
// this is key:
iss >> std::noskipws; // or:
iss.unsetf(std::ios::skipws);
Iterator f(iss), l;
std::string parsed;
if (qi::parse(f, l, entry >> -qi::eol, parsed))
{
std::cout << "Parsed: '" << parsed << "'\n";
} else
std::cout << "Failed";
if (f!=l)
std::cout << "Remaining: '" << std::string(f,l) << "'\n";
}
打印
Parsed: 'This is some single-spaced text'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.