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])

License

BSD-3-Clause

Keywords

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

Latest Posts

Remotely backing up PFsense Configuration (BASH)
FFMPEG: Converting RMVB to X264 MP4 (BASH)
Recursively print table (print_r equivalent) (LUA)
Bulk Delete Comments from (Self-Hosted) JIRA Issues (Misc)
Add a static entry to the ARP table (BASH)
SSL Cipher Hex codes to Human Readable Names (Misc)
Convert Ascii to Binary (BASH)
Intercepting Outbound DNS Queries (BASH)
Handle Google Verification files within NGinx Configuration (NGinx)
Getting WhatsApp Rich Snippet Previews Working (Misc)

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