如何从日志文件中抓取状态代码?(在 C++ 中)
How do I scrape status code from the log file? (in c++)
日志文件中的每个字符串如下所示:
44.225.84.206 - - [12/Mar/2020:07:02:43 +0530] "获取 HTTP/1.1 http://example.com/" 200 73 "-" "AWS 安全扫描程序">
我必须计算文件中的状态代码(此处为200(。
您可以通过std::regex
库使用正则表达式。"".+" (\d+)"
模式匹配任何带引号的字符串和空格后的任何数字。由于您的状态代码紧跟在带引号的字符串"GET http://example.com/ HTTP/1.1" 200
之后,它将匹配第一个数字字符直到空格,因此 73 将不匹配。请注意,如果您的日志文件在其他任何地方都包含带引号的字符串,后跟空格和数字,它也将匹配,如果需要,请修改模式。
std::regex_search()
将匹配该行并将结果存储在match
中。match.str(1)
将返回第一组;第一个()
的内容,即 200 作为字符串。如果需要,将其转换为int
。
#include <fstream>
#include <iostream>
#include <regex>
#include <vector>
int main()
{
std::ifstream log_file("statlog.txt");
std::regex re("".+" (\d+)");
std::smatch match;
std::string line;
std::vector<std::string> status_code;
while(std::getline(log_file, line)) {
if(std::regex_search(line.cbegin(), line.cend(),match, re))
status_code.push_back(match.str(1));
}
for(auto& elem : status_code) std::cout << elem << 'n';
}
这会将所有状态代码存储在字符串向量中。
当然,如果您使用的是 C++11 或更高版本,这是。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值