Lua中多个字符串分割

我有以下字符串:

example = "1,3,4-7,9,13-17"

使用这些值,我想得到下一个数组:1,3,4,5,6,7,9,13,14,15,16,17

使用以下脚本,我可以得到逗号之间的值,但怎样得到其余部分。

teststring = "1,3,4-7,9,13-17"
testtable=split(teststring, ",");
for i = 1,#testtable do
  print(testtable[i])
end;

function split(pString, pPattern)

  local Table = {}  -- 注意:在Lua-5.0中使用{n = 0}
  local fpat = "(.-)" .. pPattern
  local last_end = 1
  local s, e, cap = pString:find(fpat, 1)
  while s do
    if s ~= 1 or cap ~= "" then
      table.insert(Table,cap)
    end
    last_end = e+1
    s, e, cap = pString:find(fpat, last_end)
  end
  if last_end <= #pString then
    cap = pString:sub(last_end)
    table.insert(Table, cap)
 end
 return Table
end

输出结果

1

3

4-7

9

13-17

点赞
用户2858170
用户2858170

以下代码可以解决你的问题,前提是你的输入字符串遵循该格式。

local test = "1,3,4-7,8,9-12"
local numbers = {}
for number1, number2 in string.gmatch(test, "(%d+)%-?(%d*)") do
  number1 = tonumber(number1)
  number2 = tonumber(number2)

  if number2 then
    for i = number1, number2 do
      table.insert(numbers, i)
    end
  else
    table.insert(numbers, number1)
  end

end

首先,我们使用 string.gmatch 遍历字符串。模式匹配一个或多个数字,后面跟着一个或零个“-”,后面跟着零个或多个数字。通过使用捕获,我们确保 number1 是第一个数字,如果我们实际上有一个间隔,则 number2 是第二个数字。如果我们有一个间隔,我们使用 number1number2 的循环创建介于两者之间的数字。如果我们没有间隔,则 number2nil,我们只插入 number1

有关更多详细信息,请参阅 Lua 参考手册 - 模式string.gmatch

2018-03-08 15:56:59
用户7253993
用户7253993

下面是另一种方法:

对于testtable中的每一个元素v,执行以下操作:
  如果v中包含'-'符号,则执行以下操作:
    声明空表t
    对于v中的每个非'-'字符word,插入到表t中
    对于i从t[1]到t[2]中的每个数,打印i
  否则,直接打印v
结束
2018-03-08 16:34:31