Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading