0基础lua学习(二十一)分割字符串逗号
1.使用正则表达式分割
starNum = "asd,dfg,ghj"
resultStrList = {}
reps = ","
-- [^,]+ 正则表达式 匹配,
string.gsub(starNum,'[^'..reps..']+',function ( w )
table.insert(resultStrList,w)
end)
print(resultStrList[1])
print(resultStrList[2])
print(resultStrList[3])
console:
>lua -e "io.stdout:setvbuf 'no'" "base.lua"
asd
dfg
ghj
>Exit code: 0
2.
input = "123,456,789"
delimiter = ","
if (delimiter=='') then return false end
local pos,arr = 0, {}
for st,sp in function() return string.find(input, delimiter, pos, true) end do
table.insert(arr, string.sub(input, pos, st - 1))
pos = sp + 1
end
table.insert(arr, string.sub(input, pos))
print(arr[1])
print(arr[2])
print(arr[3])
console:
123
456
789
>Exit code: 0
3.
breakpointsStr = ","
logStr = "123,456,12312313"
local i = 0
local j = 1
t = {}
local z = string.len(breakpointsStr)
while true do
i = string.find(logStr, breakpointsStr, i + 1) -- 查找下一行
if i == nil then
table.insert(t, string.sub(logStr,j,-1))
break
end
table.insert(t, string.sub(logStr,j,i - 1))
j = i + z
end
print(t[1])
print(t[2])
print(t[3])
console:
>lua -e "io.stdout:setvbuf 'no'" "base.lua"
123
456
12312313
>Exit code: 0