Search code examples
lualua-patterns

Capture pattern multiple times between 2 strings in Lua


I'd like to capture all occurrences of a pattern between 2 strings using Lua. This is the current pattern I built:

do%(%).-(mul%(%d+%,%d+%))[don't%(%)]?

This does what I want except that it only captures a single occurrence between "do()" and "don't()"

example: do()mul(41,51)mul(1,1)don't() only mul(41,51) is captured

Is it possible to achieve what I want in Lua?


Solution

  • A capture cannot be made to repeat within a single application of a pattern.

    Instead, capture everything between your phrases, then use string.gmatch to pull out each substring.

    local s = "do()mul(41,51)mul(1,1)don't()"
    local m = s:match("do%(%)(.*)don't%(%)")
    
    if m then
        for v in m:gmatch("mul%(%d+,%d+%)") do
            print(v)
        end
    end
    
    mul(41,51)
    mul(1,1)