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個字符。
我在做什麼錯?
我以爲「(」和「)」被認爲是魔法字符? – Clavus
@Clavus:不在字符集中。在那裏,他們是文字。模式選擇不同的字符;他們不能選擇不同的字符串。這是模式和正則表達式之間的根本區別之一。 –
感謝您的信息!我只是將模式轉換爲「%^ [t%d] [%d]」。其中,再加上一張支票,應該足夠我所做的。 – Clavus