Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Lua中拆分多个字符串_Lua - Fatal编程技术网

在Lua中拆分多个字符串

在Lua中拆分多个字符串,lua,Lua,我有以下字符串: 示例=“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, pP

我有以下字符串:

示例=“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 = {}  -- NOTE: use {n = 0} in Lua-5.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
teststring=“1,3,4-7,9,13-17”
testtable=split(teststring,“,”);
对于i=1,#testtable do
打印(测试表[i])
结束;
功能拆分(pString、pPattern)
本地表={}——注意:在Lua-5.0中使用{n=0}
本地fpat=“(.-)”。。帕滕
本地最后\u端=1
局部s,e,cap=pString:查找(fpat,1)
当我们做的时候
如果s~=1或cap~='',则
表.插入(表,cap)
结束
最后一端=e+1
s、 e,cap=pString:find(fpat,last_end)
结束

如果last_end以下代码解决了您的问题,因为您的输入字符串坚持该格式

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
是第二个数字,如果我们实际有一个给定的间隔。如果我们有一个给定的间隔,我们使用for循环从
number1
number2
创建中间的数字。如果我们没有区间
number2
为零,我们只有
number1
,所以我们只插入它


请参阅Lua参考手册-有关更多详细信息,请参阅另一种方法:

for _, v in ipairs(testtable) do    
  if string.match(v,'%-') then
    local t= {}
    for word in string.gmatch(v, '[^%-]+') do
      table.insert(t, word)
    end    
    for i = t[1],t[2] do print(i) end        
  else
   print (v)
  end
end

非常感谢您提供此解决方案。这就是我一直在寻找的。请注意,如果您的模式只包含您捕获的内容,则不需要捕获。