在 lua 5.1 中使用 string.gmatch 分割字符串时包含空值匹配

我有一个逗号分隔的输入字符串,需要支持空条目。因此,像 a,b,c,,d 这样的字符串应该产生一个长度为 5 的表格,其中第 4 个值是一个空值。

一个简单的例子

str="a,b,c,,d"
count=0

for v in string.gmatch(str, '([^,]*)') do
    count = count + 1
end

print(count)

这段代码在 Lua 5.1 中输出

9

虽然只有 5 个条目。

我可以将正则表达式中的 * 改为 +,这样它就报告了 4 个条目 a,b,c,d,但是不包括空值。 Lua 5.2 中似乎已经修复了这个行为,因为上面的代码在 Lua 5.2 中运行得很好,但我被迫在 Lua 5.1 中寻找一个解决方案。

我目前的实现

function getValues(inputString)
  local result = {}

  for v in string.gmatch(inputString, '([^,]*)') do
    table.insert(result, v)
  end

  return result
end

有关如何修复的任何建议吗?

点赞
用户4984564
用户4984564
local str="a,b,c,,d"
local count=1
for value in string.gmatch(str, ',') do
    count = count + 1
end
print(count)

如果你想获取这些值,你可以这样做:

local function values(str, previous)
    previous = previous or 1
    if previous <= #str then
        local comma = str:find(",", previous) or #str+1
        return str:sub(previous, comma-1), values(str, comma+1)
    end
end
2020-04-06 07:52:47
用户3832970
用户3832970

你可以在文本后面添加逗号,并使用 ([^,]*), 模式抓取所有值:

function getValues(inputString)
  local result = {}

  for v in string.gmatch(inputString..",", '([^,]*),') do
    table.insert(result, v)
  end

  return result
end

输出结果:

a
b
c

d
2020-04-06 09:50:31