2011-08-28 73 views
1

我怎樣才能匹配以下字符串與一個表達式?Lua string.match問題?

local a =「[a 1.001523] < 1.7 | [012]> < a123> <?0?>」;

local b =「[b 2.68] < ..>」;

local c =「[b 2.68] <>」;

local d =「[b 2.68] <> <> <>>;本地名稱,netTime,參數1,參數2,參數X =字符串:匹配(?);

- (string是A或B或C或d)

的問題是,該字符串可以有不同的參數計數( 「< ...>」)和參數可以有一個數字,字符,特殊的字符或空格。 我是Lua的新手,需要學習字符串匹配,但幾個小時後我無法學習。我問你,因爲我明天需要結果,我真的很感謝你的幫助!

歡呼:)

回答

1

Lua的模式是非常有限的,你不可能有替代的表情和沒有可選組。所以這意味着你所有的參數都需要與相同的表達式匹配,如果你只寫一個模式,你需要使用固定數量的參數。檢查這tutorial,適應lua模式不需要很長時間。

您可能仍然能夠使用多種模式解析這些字符串。 ^%[(%a+)%s(%d+%.%d+)%]%s是你可以做得最好的第一部分,假設本地名稱可以有多個大寫和小寫字母。要匹配參數,請在輸入的一部分上運行多個模式,如<%s*><(%w+)>以單獨檢查每個參數。

另外得到一個正則表達式庫或解析器,這在這裏會更有用。

1

Lua模式確實有限,但如果您可以做出一些假設,則可以避開。就像如果不會有>的在爭論你可以只以上的<>所有匹配的雙循環:

local a = "[a 1.001523] <1.7 | [...]> <a123> < ? 0 ?>" 
local b = "[b 2.68] <..>" 
local c = "[b 2.68] <>" 
local d = "[b 2.68] <> < > < ?>" 

function parse(str) 
    local name,nettime,lastPos = str:match'%[(%a+)%s(%d+%.%d+)%]()' 
    local arguments={} 
    -- start looking for arguments only after the initial part in [ ] 
    for argument in str:sub(lastPos+1):gmatch('(%b<>)') do 
     argument=argument:sub(2,-2) -- strip <> 
     -- do whatever you need with the argument. Here we'll just put it in a table 
     arguments[#arguments+1]=argument 
    end 
    return name,nettime,unpack(arguments) 
end 

對於更復雜的東西,你就可以使用像LPEG的東西,像kapep說的更好。