如何使用增强精神提取修剪的文本

How to extract trimmed text using Boost Spirit?

本文关键字:修剪 文本 提取 何使用 增强      更新时间:2023-10-16

使用提升精神,我想提取一个字符串,后面跟括号中的一些数据。相关字符串由左括号中的空格分隔。不幸的是,字符串本身可能包含空格。我正在寻找一种简洁的解决方案,该解决方案返回没有尾随空格的字符串。

以下代码说明了该问题:

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <string>
#include <iostream>
namespace qi = boost::spirit::qi;
using std::string;
using std::cout;
using std::endl;
void
test_input(const string &input)
{
    string::const_iterator b = input.begin();
    string::const_iterator e = input.end();
    string parsed;
    bool const r = qi::parse(b, e,
        *(qi::char_ - qi::char_("(")) >> qi::lit("(Spirit)"),
            parsed
    );
    if(r) {
        cout << "PASSED:" << endl;
    } else {
        cout << "FAILED:" << endl;
    }
    cout << "  Parsed: "" << parsed << """ << endl;
    cout << "  Rest: "" << string(b, e) << """ << endl;
}
int main()
{
    test_input("Fine (Spirit)");
    test_input("Hello, World (Spirit)");
    return 0;
}

其输出为:

PASSED:
  Parsed: "Fine "
  Rest: ""
PASSED:
  Parsed: "Hello, World "
  Rest: ""

使用这种简单的语法,提取的字符串总是跟着一个空格(我想消除)。

解决方案应该在Spirit中起作用,因为这只是更大语法的一部分。(因此,在解析后修剪提取的字符串可能会很笨拙。

提前谢谢你。

就像评论所说的那样,在单个空格的情况下,您可以对其进行硬编码。如果您需要更加灵活宽容

我会使用带有raw的船长来"欺骗"船长以达到您的目的:

bool const r = qi::phrase_parse(b, e,
    qi::raw [ *(qi::char_ - qi::char_("(")) ] >> qi::lit("(Spirit)"),
    qi::space,
    parsed
);

这有效,并打印

PASSED:
  Parsed: "Fine"
  Rest: ""
PASSED:
  Parsed: "Hello, World"
  Rest: ""

在科里鲁现场观看

完整程序供参考:

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <string>
#include <iostream>
namespace qi = boost::spirit::qi;
using std::string;
using std::cout;
using std::endl;
void
test_input(const string &input)
{
    string::const_iterator b = input.begin();
    string::const_iterator e = input.end();
    string parsed;
    bool const r = qi::phrase_parse(b, e,
        qi::raw [ *(qi::char_ - qi::char_("(")) ] >> qi::lit("(Spirit)"),
        qi::space,
        parsed
    );
    if(r) {
        cout << "PASSED:" << endl;
    } else {
        cout << "FAILED:" << endl;
    }
    cout << "  Parsed: "" << parsed << """ << endl;
    cout << "  Rest: "" << string(b, e) << """ << endl;
}
int main()
{
    test_input("Fine (Spirit)");
    test_input("Hello, World (Spirit)");
    return 0;
}