Lua 模式在提取括号中的多个子字符串时返回错误的匹配结果

所以我遇到了一个正则表达式的问题,如下所示,我使用了正则表达式"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

所以问题在于当前的正则表达式匹配到了

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)

但是我只想匹配CreateRuntimeTxd('rick')

点赞
用户3832970
用户3832970

你需要使用

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

查看 Lua demo。_细节_:

  • CreateRuntimeTxd - 文本文字
  • %( - 一个字面值的 ( 字符
  • .- - 零个或多个字符(完成匹配所需的最少数量)
  • %) - 一个 ) 字符。

你也可以使用一个否定字符类 [^()]*(如果在 之前没有 )或 [^)]*(如果仍然可以使用 ) 字符)代替 .-

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

查看Lua demo

2021-12-24 11:23:10