如何分析文件中具有特定格式的行
How to parse for lines with specific format in a file
我最近尝试解析字幕文件以自行修改时间。格式非常简单,有效的行如下所示:
<arbitrary lines might include comments, blanks, random stuff>
<consecutively numbered ID here>
01:23:45,678 --> 01:23:47,910
<arbitrary lines might include comments, blanks, random stuff>
我怎样才能在C++中以一种优雅的方式做到这一点。我只想出了非常丑陋的解决方案。例如,要逐行读取文件,请在每个文件中搜索"-->",然后使用find(":")、find(",")和substr()的序列在这一行上运行
不过,我觉得一定有更好的方法,例如以某种方式通过代币进行拆分。如果我仍然可以解析以下行,那将是理想的:
01 : 23 :45,678 --> 01:23: 45, 910
正确。最终结果应该是变量中的每个部分(hh、mm、ss、ms)。我不一定要求完全实现。一个一般的想法和适当的实用函数的参考是完全足够的。
您只需使用std::regex
即可完成此操作。您可以定义,提取哪些令牌,正则表达式将为您执行这些操作。当然,您可以修改输入字符串。它仍然有效。您可以继续使用矢量中的数据。相当简单。
参见一些骨架代码示例:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <regex>
// Our test data (raw string). So, containing also " and so on
std::string testData(R"#(01 : 23 :45,678 --> 01:23: 45, 910 ?")#");
std::regex re(R"#((bd+b))#");
int main(void)
{
// Define the variable id as vector of string and use the range constructor to read the test data and tokenize it
std::vector<std::string> id{ std::sregex_token_iterator(testData.begin(), testData.end(), re, 1), std::sregex_token_iterator() };
// For debug output. Print complete vector to std::cout
std::copy(id.begin(), id.end(), std::ostream_iterator<std::string>(std::cout, " "));
return 0;
}
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 将"打开的CV图像"中的"颜色"转换为整数格式
- TDateTime格式在C++Builder中不会更改
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 检查不带转换的扫描格式
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- 是否可以从格式字符串中检索"width"
- clang格式:宏的缩进
- clang格式:禁用排序包含
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 将RGB图像保存为PPM格式
- 询问在设计我的手臂模拟器功能表示格式1
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 带有Protobuf序列化的C++Hazelcast:字符串不是UTF-8格式的
- 如何将strftime中的格式错误作为异常捕获
- 将CHW格式的浮点向量转换为cv::Mat
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 如何以叮当格式设置评论的行长?
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- Vulkan 中的动态顶点缓冲区格式设置