【发布时间】:2023-03-12 00:47:01
【问题描述】:
作为日志解析的结果,我有一个包含主机名和偶尔 IP 地址的字段。我需要进一步处理该字段中的数据以从主机名中解析域。 IE。如果主机名是 googleanalytics.google.com,我想尽可能高效地从中解析 google.com,因为系统每秒处理数千条日志消息。
我现在拥有的是这样的:
-- Save hostname into a temporary variable
local tempMetaValue = hostname
local count = 0
local byte_char = string.byte(".")
for i = 1, #tempMetaValue do
if string.byte(tempMetaValue, i) == byte_char then
count = count + 1
end
end
local dotCount = count
-- If there was only one dot do nothing
if dotCount == 1 then
return 0
-- Check whether there were more than one dot
elseif dotCount == 2 then
-- Get the index of the first dot
local beginIndex = string.find(tempMetaValue,".",1,true)
-- Get the substring starting after the first dot
local domainMeta = string.sub(tempMetaValue,beginIndex+1)
-- Double check that the substring exists
if domainMeta ~= nil then
-- Populate the domain meta field
end
-- If there are more than two dots..
elseif dotCount > 2 then
-- Test to see if the hostname is actually an IP address
if tempMetaValue:match("%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?") then
-- Skip the rest if an IP address was found
end
-- Get the index of the second to last dot
local beginIndex = string.find(tempMetaValue,"\.[^\.]*\.[^\.]*$")
-- Get the substring starting after the second to last dot
local domainMeta = string.sub(tempMetaValue,beginIndex+1)
-- Double check that the substring exists
if domainMeta ~= nil then
-- Populate the domain meta field
end
end
我有一种感觉,尽管他可能不是最快的解决方案。 “一种感觉”,因为在此之前我对 Lua 的经验为零,但是对于这样一个简单的任务来说似乎非常漫长。
我尝试创建一个解决方案,其中类似于拆分的操作,例如Java 将被执行,它会留下最后一个标记“未拆分”,从而留下我真正想要的部分(域),但这些尝试无济于事。因此,基本上对于该解决方案,我希望创建与主机名值中的点一样多的令牌,即 googleanalytics.google.com 将分为“googleanalytics”和“google.com”。
【问题讨论】:
-
如果您要求一般性的“我怎样才能使我的代码更好”的响应,那么这更适合codereview.stackexchange.com。仅作记录。
-
有关在 lua 中拆分字符串的方法,请查看 lua-users.org/wiki/SplitJoin
标签: string performance lua split