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

Urldecode string (LUA)
FFMPEG Convert YUV444p to YUV420p (BASH)
Forcing FFMPEG to honour segment length in HLS Stream Creator (BASH)
Force CURL to place request to a specific IP (BASH)
Set a variable only if it is undefined (Javascript)
Ignore query string with Nginx caching proxy (NGinx)
Get breakdown of UK and non-UK votes for a Parliamentary Petition (Python)
Decompress Mozilla Firefox jsonlz4 bookmark backup files (Python)
Setting Git author details for a single repo (Git)
Checking Virtual Machine Resource Allocations with Libvirt (BASH)

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