Sample does not match * (% (*.%))

I am trying to find out how templates (implemented in string.gmatch , etc.) work in Lua 5.3, from the reference guide.

(Thanks to @greatwolf for correcting my interpretation of the picture element using *.)

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

(grouped (etc.))
(Etc.)

or

grouped (etc.)
etc.

But he does nothing 😐 ( online compiler ).

 local test = '(grouped (etc))' for sub in test:gmatch '(%(.*%))*' do print(sub) end 
+5
source share
3 answers

Another possibility is using recursion:

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

I don't think you can do this with gmatch , but using %b() along with a while might work:

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

This displays your expected results for me.

+1
source
 local test = '(grouped (etc))' print( test:match '.+%((.-)%)' ) 

Here:

. +% (grab the maximum number of characters until it is% (i.e., to the last bracket, including it, where% (just leaves the bracket).

(.-)%) will return your substring to the first escaped bracket%)

+1
source

Source: https://habr.com/ru/post/1265334/


All Articles