Lua 中的分隔符和空格拆分字符串

Split String on delimiter and spaces in Lua

问题

我正在尝试对一些 Lua 源代码进行语法高亮显示,因此我试图将一串代码拆分为 table 个运算符、space 个字符和变量名。

问题是:我有一个 table 多个分隔符,我想在这些分隔符上拆分字符串,但还要保留一个分隔符条目和所有连接的 space 个字符:

示例:

"v1 *=3"

变成

{'v1', ' ', '*=', '3'}

这个问题与

但是我的问题有所不同,因为我想在一个条目中将所有分隔符的条目彼此并排放置,但我似乎无法创建正确的模式。

我尝试过的:

local delim = {",", ".", "(", ")", "=", "*"}
local s = "local variable1 *=get_something(5) if 5 == 4 then"
local p = "[^"..table.concat(delim).."%s]+"

for a in s:gsub(p, '[=13=]%0\')gmatch'%Z+' do
    print(a)
end

实际结果:

{'local', ' ', 'variable1', ' *=', 'get_something', '(', '5', ') ', 'if', ' ', '5', ' == ', '4', ' ', 'then'}

预期结果:

{'local', ' ', 'variable1', ' ', '*=', 'get_something', '(', '5', ')', ' ', 'if', ' ', '5', ' ', '==', ' ', '4', ' ', 'then'}

这是一个小区别,寻找 space 在哪里,所有连接的 space 应该在它们自己的条目中。

EDIT 以下内容似乎适用于除 *= 之外的所有内容。仍在努力,但这里是大多数其他内容的代码:

local delim = {"*=",",", ".", "(", ")", "=", " "}
local str = "local variable1 *=get_something(5) if 5 == 4 then"

local results = {}
local toutput = ""

function makeTable(str)
    for _,v in ipairs(delim) do
        str = str:gsub("([%"..v.."]+)", "`%1`")
    end
    for item in str:gmatch("[^`]+") do table.insert(results, item) end

    for _,v in ipairs(results) do
      toutput = toutput .. "'" .. v .. "',"
    end

    print("[" .. toutput .. "]")
end

makeTable(str)

它returns:

['local',' ','variable1',' ','*','=','get_something','(','5',')',' ','if',' ','5',' ','==',' ','4',' ','then',]

希望这能让你更近一步。

过了一段时间我找到了解决方案,如果有人感兴趣,就把它贴在这里。

local delim = {",", ".", "(", ")", "=", "*"}
local s = "local variable1 *=get_something(5) if 5 == 4 then"
local p = "[^"..table.concat(delim).."]+"

-- Split strings on the delimeters, but keep them as own entry
for a in s:gsub(p, '[=10=]%0\')gmatch'%Z+' do

    -- Split strings on the spaces, but keep them as own entry
    for a2 in a:gsub("%s+", '[=10=]%0\')gmatch'%Z+' do
        print(a2)
    end
end