【问题标题】:Efficiently splitting strings高效分割字符串
【发布时间】: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”。

【问题讨论】:

标签: string performance lua split


【解决方案1】:

这样的事情能满足你的要求吗?

function getdomain(str)
    -- Grad just the last two dotted parts of the string.
    local domain = str:match("%.?([^.]+%.[^.]+)$")
    -- If we have dotted parts and they are all numbers then this is an IP address.
    if domain and tonumber((domain:gsub("%.", ""))) then
        return nil
    end
    return domain
end

print(getdomain("googleanalytics.google.com"))
print(getdomain("foobar.com"))
print(getdomain("1.2.3.4"))
print(getdomain("something.else.longer.than.that.com"))
print(getdomain("foobar"))

“它是一个 IP 地址吗”测试非常愚蠢,很可能应该做一个更强大的测试,但为了快速演示。

【讨论】:

  • 谢谢你,与我以前的相比,这完全来自另一个世界。
猜你喜欢
  • 1970-01-01
  • 2020-03-07
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多