首页 > 解决方案 > 解析两种格式的文件并解析行

问题描述

我有一个巨大的文件,其中可以包含以下两种格式的行:

格式1:

*1 <int_1/string_1>:<int/string> <int_2/string_2>:<int/string> <float>

格式2:

*1 <int/string>:<int/string> <float>

因此,上述格式的可能情况是:

*1 1:2 3:4 2.3
*1 1:foo 3:bar 2.3
*1 foo:1 bar:4 2.3
*1 foo:foo bar:bar 2.3
*1 foo:foo 2.3

从以上两个格式行中,我只需要为我的代码考虑“Format1”。在读取那个巨大的文件时,跳过与“Format2”相关的行。在可能的情况下,我会考虑前 4 种情况,而不是最后一种,因为它与“Format2”匹配。所以,正则表达式应该是这样的:

(\d+)(\s+)(\\*\S+:\S+)(\s+)(\\*\S+:\S+)(\s+)(\d+)

在哪里

\d is any digit. \d+ is more than 1 digit.
\s is space. \s+ is more than 1 space.
\S is anything non-space. \S+ is anything more than 1 non-space.

在考虑了 'Format1' 行之后,我将不得不从中获取两个值:

int_1/string_1
int_2/string_2

您可以采取哪些最佳措施来应对它?

标签: c++c++11

解决方案


您可以先计算以空格分隔的字段的数量

struct Field {
    int start, stop;
};
Field fields[4];
int i = 0, nf = 0;
while (s[i]) {
    while (s[i] && isspace(s[i])) i++;
    if (!s[i]) break;
    int start = i;
    while (s[i] && !isspace(s[i])) i++;
    nf++;
    if (nf == 5) break; // Too many fields
    fields[nf-1].start = start;
    fields[nf-1].stop = i;
}
if (nf == 4) {
    // We got 4 fields, line could be acceptable
    ...
}

可能为第一个字符添加预检查,如果无效行很多'1''*'空格可以加快跳过无效行。


推荐阅读