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 个字符。

我到底做错了什么?

原文链接 https://stackoverflow.com/questions/6948048

点赞
stackoverflow用户734069
stackoverflow用户734069

Lua 模式不是正则表达式。例如,模式 [(t1)(02)] 并不意味着“匹配字符串 't1' 或 '02'”。它的意思是“匹配字符 '(', 't', '1', '0', '2' 或 ')'”。正是 Lua 模式缺乏这种特性,使得它们更容易实现(因此使得 Lua 标准库更小)。

你已经达到了 Lua 模式可分析的极限。如果你需要正则表达式,我建议你下载一个实现它们的 Lua 模块。

2011-08-04 20:58:56