c++ - 使用正则表达式从 C++ 中的一行文本中提取数据

标签 c++ regex

我有一个格式的文本文件:

number tab word tab word tab junk
number tab word tab word tab junk
number tab word tab word tab junk
number tab word tab word tab junk
number tab word tab word tab junk

对于每一行,我想将数字放入 uint32_t 中,然后将这两个词放入字符串中,然后忽略该行的其余部分。我可以通过将文件加载到内存中然后一次处理一个字节来做到这一点,但我相信一个可爱的正则表达式可以为我做到这一点。有什么想法吗?

我在 C++ 中工作,在 Xcode 中使用 #include - 这是一个命令行工具,因此没有实际输出,我只是存储数据以与其他数据进行比较。

最佳答案

extern bool DoStuff(unsigned n, 
                    const std::string &s0, 
                    const std::string &s1);

bool ProcessFile(const std::string &sFileName)
{
    std::ifstream ifs(sFileName);
    if (!ifs)
        return false;

    while (ifs)
    {
        unsigned n;
        std::string s0, s1;
        ifs >> n >> s0 >> s1;
        if (ifs.bad() || !DoStuff(n, s0, s1))
            return false;
        ifs.ignore(std::numeric_limits<int>::max(), '\n');
    }
    return !ifs.bad();
}

关于c++ - 使用正则表达式从 C++ 中的一行文本中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344062/

相关文章:

c++ - 与 get_instance() 分离的单例构造函数

_water_glass 的 javascript 正则表达式模式

c# - 代号困惑

正则表达式匹配问号后的所有内容?

c++ - 在 C++ 中使用迭代器导航 map

c++ - 如何在 QListWidget 中为 QStringList 的每个项目显示一个 QLabel 和另一个 QString?

python - 问题匹配包含撇号的字符串

Python字符串分割多个括号

c++ - 排序 vector <const char *>

c++ - 未定义的运算符引用 >>