补充测试:
std::string output = R"(
Basic ACL 2001, 1 rule
Acl’s step is 5
rule 5 permit source 192.168.1.0 0.0.0.255
)";
写个c++代码,正则匹配出 类型 Basic,名称:2001,规则类型: permit, ip:192.168.1.0,掩码:0.0.0.255,用nlohmann/json.hpp库 json输出
运行结果:
root@jxh-virtual-machine:/mnt/hgfs/tq_work/2-devolepment_code/1-network_exchange/2-test/10-regex_s5730_acl#
root@jxh-virtual-machine:/mnt/hgfs/tq_work/2-devolepment_code/1-network_exchange/2-test/10-regex_s5730_acl# g++ regex_acl.cpp
root@jxh-virtual-machine:/mnt/hgfs/tq_work/2-devolepment_code/1-network_exchange/2-test/10-regex_s5730_acl#
root@jxh-virtual-machine:/mnt/hgfs/tq_work/2-devolepment_code/1-network_exchange/2-test/10-regex_s5730_acl#
root@jxh-virtual-machine:/mnt/hgfs/tq_work/2-devolepment_code/1-network_exchange/2-test/10-regex_s5730_acl# ./a.out
{
"IP": "192.168.1.0",
"Mask": "1.",
"Name": "2001",
"RuleType": "permit",
"Type": "Basic"
}
*/
#include
#include
#include
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
std::string output = R"(
Basic ACL 2001, 1 rule
Acl’s step is 5
rule 5 permit source 192.168.1.0 0.0.0.255
)";
// 定义正则表达式模式来匹配类型、名称、规则类型、IP、掩码
// std::regex pattern(R"(Basic (\w+) (\d+), \d+ rule.+rule \d+ (\w+) source (\d+.\d+.\d+.\d+) (\d+.\d+.\d+.\d+))“);
//std::regex pattern(R”(Basic (\w+) (\d+), \d+ rule\r?\n.rule (\d+))");
std::regex pattern(R"(\b(\w+) ACL (\w+),\s+\d\s+rule+\n.+\n+\s+rule+\s\d\s+(\w+) source ((\d{1,3}\.){3}\d{1,3})\s((\d{1,3}\.){3}\d{1,3})\b)");
std::smatch match;
if (std::regex_search(output, match, pattern)) {
std::string type = match[1];
std::string name = match[2];
std::string ruleType = match[3];
std::string ip = match[4];
std::string mask = match[5];
// 创建 JSON 对象
json aclInfo;
aclInfo["Type"] = type;
aclInfo["Name"] = name;
aclInfo["RuleType"] = ruleType;
aclInfo["IP"] = ip;
aclInfo["Mask"] = mask;
// 输出 JSON 数据
std::cout << aclInfo.dump(4) << std::endl;
} else {
std::cout << "No match found." << std::endl;
}
return 0;
}