【发布时间】:2017-12-11 12:44:05
【问题描述】:
我对 C++ 比较陌生,但我正在努力解决以下问题:
我正在解析来自 iptables 的 syslog 消息。每条消息看起来像:192.168.1.1:20200:Dec 11 15:20:36 SRC=192.168.1.5 DST=8.8.8.8 LEN=250
而且我需要快速(因为新消息来得很快)解析字符串以获取 SRC、DST 和 LEN。
如果它是一个简单的程序,我会使用std::find 来查找STR 子字符串的索引,然后在循环中将每个下一个字符添加到数组中,直到遇到空格。然后我会为DST 和LEN 做同样的事情。
例如,
std::string x = "15:30:20 SRC=192.168.1.1 DST=15.15.15.15 LEN=255";
std::string substr;
std::cout << "Original string: \"" << x << "\"" << std::endl;
// Below "magic number" 4 means length of "SRC=" string
// which is the same for "DST=" and "LEN="
// For SRC
auto npos = x.find("SRC");
if (npos != std::string::npos) {
substr = x.substr(npos + 4, x.find(" ", npos) - (npos+4));
std::cout << "SRC: " << substr << std::endl;
}
// For DST
npos = x.find("DST");
if (npos != std::string::npos) {
substr = x.substr(npos + 4, x.find(" ", npos) - (npos + 4));
std::cout << "DST: " << substr << std::endl;
}
// For LEN
npos = x.find("LEN");
if (npos != std::string::npos) {
substr = x.substr(npos + 4, x.find('\0', npos) - (npos + 4));
std::cout << "LEN: " << substr << std::endl;
}
但是,在我的情况下,我需要非常快速地完成此操作,最好是一次迭代。
你能给我一些建议吗?
【问题讨论】:
-
关于正则表达式的一点警告:有句话类似于“你有一个问题。你用正则表达式解决它。现在你有 两个 问题”。虽然正则表达式可以是一个强大的工具,但它也非常先进,而且绝对不平凡。正则表达式很容易出错,只能作为最后的努力使用。尤其是初学者,甚至是中级程序员。
-
你有证据表明你的程序太慢了吗?