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

如何在Lua中正确匹配带或不带引号的目标文件路径?

在Lua中正确匹配带/不带引号的路径

核心问题是原正则里的%g+会匹配包括引号在内的所有非空白字符,加上Lua没有非贪婪的+运算符,导致带引号的场景会把末尾引号也包含在结果里。这里提供两种简单的解决方法:

方案一:使用排除型字符集

直接指定捕获组只匹配非引号、非空白的字符,避免捕获到引号:

local s1 = "bibliography: /home/user/file.lib"
local s2 = 'bibliography: "/home/user/file.lib"'

-- 匹配正则
local path1 = string.match(s1, 'bibliography: "?([^"\s]+)"?')
local path2 = string.match(s2, 'bibliography: "?([^"\s]+)"?')

print(path1) -- 输出:/home/user/file.lib
print(path2) -- 输出:/home/user/file.lib

原理

[^"\s]是排除型字符集,表示匹配任何既不是双引号也不是空白的字符。当遇到带引号的字符串时,捕获组会在末尾引号处停止匹配;不带引号时,会匹配到字符串结束或下一个空白字符,完全符合需求。

方案二:分支匹配(明确区分场景)

通过分支正则优先匹配带引号的格式,再匹配不带引号的格式,逻辑更清晰:

local s1 = "bibliography: /home/user/file.lib"
local s2 = 'bibliography: "/home/user/file.lib"'

-- 定义提取路径的函数
local function extract_bib_path(str)
    -- 先匹配带引号的情况,再匹配不带的
    local quoted_path, plain_path = string.match(str, 'bibliography: "([^"]+)"|bibliography: (%g+)')
    return quoted_path or plain_path
end

print(extract_bib_path(s1)) -- 输出:/home/user/file.lib
print(extract_bib_path(s2)) -- 输出:/home/user/file.lib

原理

正则的第一部分bibliography: "([^"]+)"专门匹配带引号的格式,用[^"]+确保捕获的内容不包含引号;如果匹配失败,再走第二部分bibliography: (%g+)匹配不带引号的格式,最终返回第一个有效结果。

内容的提问来源于stack exchange,提问作者robertspierre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 00:34:51