c++ - 使用 boost 正则表达式解析文本文件

标签 c++ regex parsing boost expression

我正在尝试使用 boost::regex 库在 C++ 中解析文本文件。

我试图将这一行解析到我的程序中: 1_3,1,3,0

  • 1_3需要成为字符串中的名字
  • 1需要成为char中的X坐标
  • 3需要成为char中的Y坐标
  • 0,需要成为一个函数的成本,也是一个字符

你们知道要写什么火柴吗?

我试过这个但是没用:

boost::regex rgex("^([0-9]),([0-9]+),([0-9]+),([0-9]+).*");

提前致谢

最佳答案

我不会使用正则表达式执行此操作,这让您不得不进行所有类型转换。

我会直接解析成 vector<>结构

struct record {
    std::string name;
    char x, y, cost;
};

有了 Boost Spirit,喜欢

std::vector<record> data;
bool ok = qi::phrase_parse(f, l,
    (qi::lexeme[+~qi::char_(',')] >> ',' >> qi::int_ >> ',' >> qi::int_ >> ',' >> qi::int_) % qi::eol,
    qi::blank,
    data);

if (ok)
{
    std::cout << "Parsed success: " << data.size() << " records\n";
    for(auto& r : data)
        std::cout << r << "\n";
}

请注意,此方法接受并忽略额外的空格 ( qi::blank )。

查看 Live On Coliru 打印:

Parsed success: 11 records
1_3 1   3   0
16_92   16  92  76
8_31    8   31  13
3_45    3   45  46
12_67   12  67  66
17_27   17  27  2
7_72    7   72  74
0_36    0   36  25
18_30   18  30  50
6_35    6   35  19
16_5    16  5   50

完整代码

供引用

#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

struct record {
    std::string name;
    char x, y, cost;

    friend std::ostream& operator<<(std::ostream& os,const record& r) {
        return os << r.name << "\t" << int(r.x) << "\t" << int(r.y) << "\t" << int(r.cost);
    }
};

BOOST_FUSION_ADAPT_STRUCT(record, (std::string, name)(char, x)(char, y)(char, cost))

int main()
{
    std::istringstream iss(
            "1_3,1,3,0\n"
            "16_92,16,92,76\n"
            "8_31,8,31,13\n"
            "3_45,3,45,46\n"
            "12_67,12,67,66\n"
            "17_27,17,27,2\n"
            "7_72,7,72,74\n"
            "0_36,0,36,25\n"
            "18_30,18,30,50\n"
            "6_35,6,35,19\n"
            "16_5,16,5,50"
        );

    boost::spirit::istream_iterator f(iss >> std::noskipws), l;

    std::vector<record> data;
    bool ok = qi::phrase_parse(f, l,
        (qi::lexeme[+~qi::char_(',')]
         >> ',' >> qi::int_ >> ',' >> qi::int_ >> ',' >> qi::int_
        ) % qi::eol,
        qi::blank,
        data);

    if (ok)
    {
        std::cout << "Parsed success: " << data.size() << " records\n";
        for(auto& r : data)
            std::cout << r << "\n";
    } else
    {
        std::cout << "Parse failed\n";
    }

    if (f!=l)
    {
        std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
    }
}

关于c++ - 使用 boost 正则表达式解析文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24087338/

相关文章:

C++ - 为什么删除后将对象设置为空?

C++ 头文件(基础)

c++ - 编译 Spirit 示例时出错

c++ - 虽然运算符重载不能通过引用返回?

javascript - Jquery HTML 表本身

javascript - 奇怪的 while 循环元组

javascript - 删除字符串中不需要的部分。正则表达式/JS

Regex Notepad++ 删除除 IP 以外的所有内容

ruby - iCalendar 的正则表达式解析(Ruby 正则表达式)

android - 不从资源解析布局并在运行时设置它