我有以下字符串:
例= "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
输出
1
3.
4-7
9
13-17
发布于 2018-03-08 15:56:59
下面的代码解决了您的问题,因为您的输入字符串坚持这种格式
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
是第二个数字,如果我们确实有一个给定的间隔。如果我们有一个给定的间隔,我们在使用从number1
到number2
的for循环之间创建数字。如果我们没有间隔,number2
是零,我们只有number1
,所以我们只插入它。
详情请参阅Lua参考手册- 模式及string.gmatch
发布于 2018-03-08 16:34:31
以下是另一种方法:
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
https://stackoverflow.com/questions/49176627
复制相似问题