2015-02-09 77 views
2

作爲日誌分析的結果,我有一個包含主機名和偶爾IP地址的字段。我需要進一步處理該字段中的數據以解析主機名中的域。即如果主機名是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將被執行,並且它會將最後一個標記「unsplit」留下,從而讓我留下我實際需要的部分(域),但是沒有得到這些嘗試。因此,基本上對於該解決方案,我希望創建與主機名值中的點數一樣多的令牌,即將googleanalytics.google.com分成「googleanalytics」和「google.com」。

+1

如果你要求一般的「我怎樣才能讓我的代碼更好」的迴應,那麼這更適合https://codereview.stackexchange.com。只是爲了記錄。 – 2015-02-09 13:35:24

+0

有關如何在lua中拆分字符串的方法,請參閱http://lua-users.org/wiki/SplitJoin – 2015-02-09 13:36:02

回答

2

做這樣的事情做你想做的事情?

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地址」的測試是非常愚蠢的,應該很容易做出一個更強大的測試,但對於快速演示,供應。

+0

謝謝,完美的解決方案完全來自與以前相比完全不同的世界。 – treiman 2015-02-09 20:28:22