Split a string using string.gmatch() in Lua

感情迁移 提交于 2019-12-03 04:11:19
local s = "one;two;;four"
local words = {}
for w in (s .. ";"):gmatch("([^;]*);") do 
    table.insert(words, w) 
end

By adding one extra ; at the end of the string, the string now becomes "one;two;;four;", everything you want to capture can use the pattern "([^;]*);" to match: anything not ; followed by a ;(greedy).

Test:

for n, w in ipairs(words) do
    print(n .. ": " .. w)
end

Output:

1: one
2: two
3:
4: four
function split(str,sep)
    local array = {}
    local reg = string.format("([^%s]+)",sep)
    for mem in string.gmatch(str,reg) do
        table.insert(array, mem)
    end
    return array
end
local s = "one;two;;four"
local array = split(s,";")

for n, w in ipairs(array) do
    print(n .. ": " .. w)
end

result:

1:one

2:two

3:four

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!