我有這個字串
"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 呢?
uj5u.com熱心網友回復:
這個任務不能用一個單一的 Lua 模式來完成,但可以用幾個模式鏈來完成。引數不能包含 bytes和-
這些特殊字符用于臨時替換。text\0\1\2
local function ExtractArgs(text)
local arguments = {}
for argument in
('""'..text:gsub("\\?.", {['\\"']="\1"}))
:gsub('"(.-)"([^"]*)', function(q,n) return "\2"..q..n:gsub("%s ", "\0") end)
:sub(2)
:gmatch"%Z "
do
argument = argument:gsub("\1", '"'):gsub("\2", ""):gsub("\\(.)", "%1")
print(argument)
arguments[#arguments 1] = argument
end
return arguments
end
ExtractArgs[[argument \"\\ "" "some argument" "some argument with a quotation mark \" in here \\"]]
輸出:
argument
"\
some argument
some argument with a quotation mark " in here \
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496156.html
