You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua中提取引号间子串并正确处理转义"的实现方法

Lua参数提取功能实现问题

我有如下字符串:

"argument \\\" \"some argument\" \"some argument with a quotation mark \\\" in here \""

该字符串打印输出结果为:

argument \" "some argument" "some argument with a quotation mark \" in here"

我需要提取其中的所有参数,最终存储为如下结构:

> [1] = "argument",
> [2] = """",
> [3] = "some argument",
> [4] = "some argument with a quotation mark " in here"

现有实现代码

以下是我目前编写的实现代码:

function ExtractArgs(text)
    local skip = 0
    local arguments = {}
    local curString = ""

    for i = 1, text:len() do
        if (i <= skip) then continue end

        local c = text:sub(i, i)
        
        if (c == "\\") and (text:sub(i+1, i+1) == "\"") then
            continue
        end
        
        if (c == "\"") and (text:sub(i-1, i-1) ~= "\\") then
            local match = text:sub(i):match("%b\"\"")
            
            if (match) and (match:sub(#match-1,#match-1) ~= "\\") then
                curString = ""
                skip = i + #match
                arguments[#arguments + 1] = match:sub(2, -2)
            else
                curString = curString..c
            end
        elseif (c == " " and curString ~= "") then
            arguments[#arguments + 1] = curString
            curString = ""
        else
            if (c == " " and curString == "") then
                continue
            end

            curString = curString..c
        end
    end

    if (curString ~= "") then
        arguments[#arguments + 1] = curString
    end
    
    return arguments
end

测试调用代码如下:

print(ExtractArgs("argument \\\" \"some argument\" \"some argument with a quotation mark \\\" in here\""))

现存问题

当前代码可以正确提取不在引号范围内的转义\",但无法正确处理引号内部的转义\"字符。已知正则表达式\"([^\"\\]*(?:\\.[^\"\\]*)*)\"可实现该匹配需求,请问在Lua中应当如何正确实现该功能?

内容的提问来源于stack exchange,提问作者karl-police

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 08:06:20