lualua-patterns

Lua pattern returns wrong match when fetching multiple substrings between brackets


So I have this problem with a regex. As seen below I use the regex"CreateRuntimeTxd%(.*%)"

local _code = [[
Citizen.CreateThread(function()
    local dui = CreateDui("https://www.youtube.com/watch?v=dQw4w9WgXcQ", 1920, 1080)
    local duiHandle = GetDuiHandle(dui)
    CreateRuntimeTextureFromDuiHandle(CreateRuntimeTxd('rick'), 'nevergonnagiveuup', duiHandle)

    while true do
        Wait(0)
        DrawSprite('rick', 'nevergonnagiveuup', 0.5, 0.5, 1.0, 1.0, 0, 255, 255, 255, 255)
    end
end)
]]

for match in string.gmatch(_code, "CreateRuntimeTxd%(.*%)") do
    print(match)
end

So the problem is that the current regex matches

CreateRuntimeTxd('rick'), 'nevergonnagiveuup', duiHandle)

    while true do
        Wait(0)
        DrawSprite('rick', 'nevergonnagiveuup', 0.5, 0.5, 1.0, 1.0, 0, 255, 255, 255, 255)
    end
end)

but i only want it to match CreateRuntimeTxd('rick')


Solution

  • You need to use

    for match in string.gmatch(_code, "CreateRuntimeTxd%(.-%)") do
        print(match)
    end
    

    See the Lua demo. Details:

    • CreateRuntimeTxd - a literal text
    • %( - a literal ( char
    • .- - zero or more characters (the least amount needed to complete a match)
    • %) - a ) char.

    You may also use a negated character class, [^()]* (if there can be no ( and ) before )) or [^)]* (if ) chars are still expected) instead of .-:

    for match in string.gmatch(_code, "CreateRuntimeTxd%([^()]*%)") do
        print(match)
    end
    

    See this Lua demo.