无法匹配模式*(%(*.%))

我正在尝试学习Lua 5.3中实现的模式(使用string.gmatch等),从参考手册中了解它们的工作原理。

(感谢@greatwolf纠正我关于模式项使用*的解释。)

我尝试匹配'(.*)*'(由包围的子字符串;例如, '(分组(等等))'),以便记录

(已分组(等等))

(等等)

已分组(等等)

等等

但它什么也没做(在线编译器)。

local test ='(组(等等))'

for sub in test:gmatch '(.*)*' do
printsubend
点赞
用户1442917
用户1442917

我认为你不能用 gmatch 来做这个,但是使用 %b()while 循环可能可以:

local pos, _, sub = 0
while true do
  pos, _, sub  = ('(grouped (etc))'):find('(%b())', pos+1)
  if not sub then break end
  print(sub)
end

这对我来说可以打印出你期望的结果。

2017-03-11 22:35:51
用户7504558
用户7504558
local test = '(grouped (etc))'

print(test:match('.+%((.-)%)'))

在这里:

.+%( 捕获最多数量的字符,直到 %(,也就是直到最后一个包括它的括号,其中 %( 只是对括号进行转义。

(.-)%) 将返回你到第一个转义括号 %) 的子字符串。

2017-03-12 05:45:27
用户3735873
用户3735873

另一种可能性 - 使用递归:

function show(s)
  for s in s:gmatch '%b()' do
    print(s)
    show(s:sub(2,-2))
  end
end

show '(grouped (etc))'
2017-03-12 22:19:51