Split a string using string.gmatch() in Lua

后端 未结 3 1262
南笙
南笙 2020-12-15 11:35

There are some discussions here, and utility functions, for splitting strings, but I need an ad-hoc one-liner for a very simple task.

I have the following string:

3条回答
  •  情歌与酒
    2020-12-15 12:11

    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

提交回复
热议问题