解析引用的字符串仅在某些情况下有效

时间:2013-08-16 16:00:59

标签: c++ boost-spirit boost-spirit-qi

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

#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

1 个答案:

答案 0 :(得分:2)

正如之前所说的 cv_and_he - 您的*char_吃了所有内容,并且从“更新的”解析器序列中您可以猜到它为什么不起作用: - )< / p>

#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;
}