Split string on Delimiter



Published: 2017-05-23 12:08:18 +0000
Categories: LUA,

Language

LUA

Description

Basic function to split a string on a delimiter in LUA. Syntax is like PHP's explode - delimiter then string

Returns a table of the identified substrings

One known limitation is that it won't include an empty key where two delimiters occur in sequence - e.g. 'foo,,bar' - will return a table with two entries instead of 3. But I didn't need that behaviour when I wrote it, so didn't spend any extra time on it

Similar to

  • PHP explode()
  • Python split()
  • Javascript split()

Snippet

function strSplit(delim,str)
    local t = {}

    for substr in string.gmatch(str, "[^".. delim.. "]*") do
        if substr ~= nil and string.len(substr) > 0 then
            table.insert(t,substr)
        end
    end

    return t
end

Usage Example

local s = "foo?bar??sed"
local t = strSplit("?",s)
print(t[1])
print(t[2])
print(t[3])

Video Example

License

BSD-3-Clause

Keywords

split, explode, divide, string, seperator, delimiter,

Latest Posts


Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, yr4pnhounvdybotb.onion and snippets.6zdgh5a5e6zpchdz.onion