c++ - 解析两种格式的文件并解析行
问题描述
我有一个巨大的文件,其中可以包含以下两种格式的行:
格式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
您可以采取哪些最佳措施来应对它?
解决方案
您可以先计算以空格分隔的字段的数量
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'
,'*'
空格可以加快跳过无效行。
推荐阅读
- java - 找不到符号 - 类 InventoryItem
- git - 每次推送时如何提示 git 用户登录?
- javascript - Google 地图 API - 按邮政编码搜索
- java - 在 Java 中嵌套 CompletionStages 以使内部块在外部块之前运行
- python - 没有名为 pymysql 的模块 - aws 无服务器框架
- c# - 从文件中读取时,索引超出了数组的范围
- python - 如何检测像 ID 卡中的全息图覆盖?
- r - 如何将输入变量传递给 R 中的 SPARQL 语句?
- web-services - Telerik Reporting Web 服务数据源无法设置标头
- javascript - 表单提交不完整后如何保留表单数据