3

在尝试解析简单的带引号的字符串时,我遇到了一些奇怪的事情。所以我编写了这个简单的解析器,可以成功解析带引号的字符串,比如"string"or ""

#include <iostream>
#include "boost/spirit/include/qi.hpp"

namespace qi      = boost::spirit::qi;
namespace iso8859 = boost::spirit::iso8859_1;


int main( int argc, char* argv[] )
{
    using namespace qi;

    std::string input = "\"\"";

    std::string::const_iterator front = input.cbegin();
    std::string::const_iterator end   = input.cend();
    bool parseSuccess = phrase_parse( front, end,
                                      '\"' >> *~char_('\"') >> '\"',
                                      iso8859::space );

    if ( front != end )
    {
        std::string trail( front, end );
        std::cout << "String parsing trail: " << trail << std::endl;
    }

    if ( !parseSuccess )
        std::cout << "Error parsing input string" << std::endl;

    std::cout << "Press enter to exit" << std::endl;
    std::cin.get();
    return 0;
}

这一切都很好,但是当我扩展解析规则以解析引用字符串之前的内容时,它突然中断了..

因此,例如,这会成功解析:

std::string input = "normalString 10.0 1.5 1.0 1.0 1.0 1.0" 使用解析规则:

*char_ >> *double_

现在,如果我将此规则与带引号的字符串规则结合起来:

std::string input = "normalString 10.0 1.5 1.0 1.0 1.0 1.0 \"quotedString\""

使用解析规则:

*char_ >> *double_ >> '\"' >> *~char_('\"') >> '\"'

它突然不再起作用并且解析失败。我不知道为什么。谁能解释一下?

编辑:以防万一,我使用的是 Boost 1.53

4

1 回答 1

2

正如cv_and_he前面所说 - 你*char_吃掉了所有东西,从“更新的”解析器序列中你可以猜到它为什么不起作用:-)

#include <iostream>
#include "boost/spirit/include/qi.hpp"

namespace qi      = boost::spirit::qi;
namespace iso8859 = boost::spirit::iso8859_1;

int main( int argc, char* argv[] )
{
    using namespace qi;

    std::vector< std::string > inputVec{
        "normalString 10.0 1.5 1.0 1.0 1.0 1.0 \"quotedString\"",
        "normalString \"quotedString\"",
        "10.0 1.5 1.0 1.0 1.0 1.0 \"quotedString\"",
        "10.0 1.5 1.0 1.0 1.0 1.0 \"\"",
        "\"\""};

    for( const auto &input : inputVec )
    {
        std::string::const_iterator front = input.cbegin();
        std::string::const_iterator end   = input.cend();
        bool parseSuccess = phrase_parse( front, end,
            no_skip [ *(char_ - space - double_ - '\"') ] 
            >> *double_ >> '\"' >> *~char_('\"') >> '\"',
          iso8859::space );    
        if ( parseSuccess && front == end)
            std::cout << "success:";
        else
            std::cout << "failure:";
         std::cout << "`" << input << "`" << std::endl;
    }
    return 0;
}
于 2013-08-16T19:44:51.837 回答