2011-08-04 67 views
1

我有兩段代碼根據模式分解字符串。Lua子模式匹配奇數

第一招:

local test = "whop^1whap^2whup" 
local pattern = "%^[12]" 
local lastpos = 1 

for startpos, endpos in string.gmatch(test, "()"..pattern.."()") do 


    print("pos: "..startpos..","..endpos) 
    print("str: "..string.sub(test,lastpos,startpos-1)) 
    print("match: "..string.sub(test,startpos,endpos-1)) 

    lastpos = endpos 

end 

這一次打破了串繞^ 1 ^或2。它輸出:

pos: 5,7 
str: whop 
match: ^1 
pos: 11,13 
str: whap 
match: ^2 

第二個版本是這樣的:

local test = "whop^t1whap^02whup" 
local pattern = "%^[(t1)(02)]" 
local lastpos = 1 

for startpos, endpos in string.gmatch(test, "()"..pattern.."()") do 


    print("pos: "..startpos..","..endpos) 
    print("str: "..string.sub(test,lastpos,startpos-1)) 
    print("match: "..string.sub(test,startpos,endpos-1)) 

    lastpos = endpos 

end 

這一個應該分手的^ T1或^ 02的字符串。相反,我得到這樣的:

pos: 5,7 
str: whop 
match: ^t 
pos: 12,14 
str: 1whap 
match: ^0 

我注意到,第一POS(5,7)是完全一樣的,在第一代碼段,即使圖案長度應該是3個字符。

我在做什麼錯?

回答

4

Lua模式不是正則表達式。例如,模式[(t1)(02)]並不意味着「匹配字符串't1'或'02'」。它意味着「匹配字符'(','t','1','0','2'或')'」。在Lua模式中缺少這樣的功能,使它們更容易實現(因此使Lua標準庫變得更小)。

你已經達到了Lua模式的分析能力的極限。如果你需要正則表達式,我建議你下載一個實現它們的Lua模塊。

+0

我以爲「(」和「)」被認爲是魔法字符? – Clavus

+1

@Clavus:不在字符集中。在那裏,他們是文字。模式選擇不同的字符;他們不能選擇不同的字符串。這是模式和正則表達式之間的根本區別之一。 –

+0

感謝您的信息!我只是將模式轉換爲「%^ [t%d] [%d]」。其中,再加上一張支票,應該足夠我所做的。 – Clavus