模式不匹配*(%(*。%))

时间:2017-03-11 22:12:10

标签: lua lua-patterns

我正在尝试从reference manual了解模式(在string.gmatch等中实现)在Lua 5.3中是如何工作的。

(感谢@greatwolf使用*来纠正我对模式项目的解释。)

我要做的是匹配'(%(.*%))*'(由包围的子字符串;例如,'(grouped (etc))'),以便记录

  

(分组(等))
  (等)

  

分组(等)
  等

但它没有做任何事情(online compiler)。

local test = '(grouped (etc))'

for sub in test:gmatch '(%(.*%))*' do
    print(sub)
end

3 个答案:

答案 0 :(得分:2)

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

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

show '(grouped (etc))'

答案 1 :(得分:1)

我认为您无法使用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

这会打印出您的预期结果。

答案 2 :(得分:1)

local test = '(grouped (etc))'

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

下面:

。 +%(捕获最大字符数,直到它%(即直到最后一个括号包括它,其中%(只是逃避括号。

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