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 个字符。
我做错了什么?
I have two pieces of code that break up a string based on the patterns.
First one:
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
This one breaks up the string around ^1 or ^2. It outputs:
pos: 5,7
str: whop
match: ^1
pos: 11,13
str: whap
match: ^2
The second version is this:
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
This one is SUPPOSED to break up the string at ^t1 or ^02. Instead I get this:
pos: 5,7
str: whop
match: ^t
pos: 12,14
str: 1whap
match: ^0
I noticed that the first pos (5,7) is exactly the same as in the first piece of code, even though the pattern length should be 3 characters.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Lua 模式不是正则表达式。例如,模式
[(t1)(02)]
并不意味着“匹配字符串 't1' 或 '02'”。它的意思是“匹配字符‘(’、‘t’、‘1’、‘0’、‘2’或‘)’”。正是 Lua 模式中缺乏这样的功能,使得它们更容易实现(因此使得 Lua 标准库更小)。您已经达到了 Lua 模式解析能力的极限。如果你需要正则表达式,我建议你下载一个实现它们的Lua模块。
Lua patterns are not regular expressions. For example, the pattern
[(t1)(02)]
does not mean "match the strings 't1' or '02'". It means "match the characters '(', 't', '1', '0', '2', or ')'". It is the lack of features like this in Lua patterns that make them much easier to implement (and therefore makes the Lua standard library smaller).You have reached the limits of the parse-ability of Lua patterns. If you need regular expressions, I suggest you download a Lua module that implements them.