Search code examples
lualua-patterns

Pattern not matching *(%(*.%))


I'm trying to learn how patterns (implemented in string.gmatch, etc.) do work in Lua 5.3, from the reference manual.

(Thanks @greatwolf for correcting my interpretation about the pattern item using *.)

What I'm trying to do is to match '(%(.*%))*' (substrings enclosed by ( and ); for example, '(grouped (etc))'), so that it logs

(grouped (etc))
(etc)

or

grouped (etc)
etc

But it does nothing 😐 (online compiler).

local test = '(grouped (etc))'

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

Solution

  • Another possibility -- using recursion:

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