gpt4 book ai didi

string - Lua:将字符串分割成单词,除非引用

转载 作者:行者123 更新时间:2023-12-02 02:20:33 29 4
gpt4 key购买 nike

所以我有以下代码来在空格之间分割字符串:

text = "I am 'the text'"
for string in text:gmatch("%S+") do
print(string)
end

结果:

I
am
'the
text'

但我需要这样做:

I
am
the text --[[yep, without the quotes]]

我该怎么做?

编辑:只是为了补充问题,其想法是将参数从一个程序传递到另一个程序。这是我正在处理的拉取请求,目前正在审核中:https://github.com/mpv-player/mpv/pull/1619

最佳答案

可能有一些方法可以通过巧妙的解析来做到这一点,但另一种方法可能是跟踪简单状态并基于对引用片段的检测来合并片段。像这样的事情可能会起作用:

local text = [[I "am" 'the text' and "some more text with '" and "escaped \" text"]]
local spat, epat, buf, quoted = [=[^(['"])]=], [=[(['"])$]=]
for str in text:gmatch("%S+") do
local squoted = str:match(spat)
local equoted = str:match(epat)
local escaped = str:match([=[(\*)['"]$]=])
if squoted and not quoted and not equoted then
buf, quoted = str, squoted
elseif buf and equoted == quoted and #escaped % 2 == 0 then
str, buf, quoted = buf .. ' ' .. str, nil, nil
elseif buf then
buf = buf .. ' ' .. str
end
if not buf then print((str:gsub(spat,""):gsub(epat,""))) end
end
if buf then print("Missing matching quote for "..buf) end

这将打印:

I
am
the text
and
some more text with '
and
escaped \" text

已更新以处理混合和转义引号。已更新以删除引号。已更新以处理引用的单词。

关于string - Lua:将字符串分割成单词,除非引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28664139/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com