explode

function explode( str, delimiter [, limit] ) --> strlst

Description

Returns an array table of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

Parameters

str

The string that should be split.

delimiter

The boundary string.

limit

If limit is set and positive, the returned array table will contain a maximum of limit elements with the last element containing the rest of string. If the limit parameter is negative, all components except the last -limit are returned. If the limit parameter is zero, then this is treated as 1. If limit is not defined uses the function 4294947296.

Return Values

strlst

An array table of strings created by splitting the string parameter on boundaries formed by the delimiter. If delimiter is an empty string (""), will the function return false.

Code

--ZFUNC-explode-v1
local function explode( str, delimiter, limit ) --> strlst

   limit = limit or 4294967296
   if limit == 0 then limit = 1 end
   if limit == 1 then return { str } end

   local strlst = {}
   local position = 1
   local s, e = string.find( str, delimiter, position, true )
   local cond = function( s, i ) return s end
   if limit > 0 then
      cond = function( s, i ) return s and i < limit - 1 end
   end

   while cond( s, #strlst ) do
      table.insert( strlst, string.sub( str, position, s-1 ) )
      position = e + 1
      s, e = string.find( str, delimiter, position, true )
   end

   if position <= #str then
      table.insert( strlst, string.sub( str, position ) )
   end

   if position > #str then
      table.insert( strlst, "" )
   end

   if limit < 0 then
      for i = 1, math.abs( limit ) do
         table.remove( strlst )
      end
   end

   return strlst
end

return explode

Examples

local t = require( "taptest" )
local explode = require( "explode" )
local same = require( "same" )

str = "one|two|three|four"

res = explode( str, "|" )
t( same( res, { "one", "two", "three", "four" } ), true )


res = explode( str, "|", 2 )
t( same( res, { "one", "two|three|four" } ), true )

res = explode( str, "|", -1 )
t( same( res, { "one", "two", "three" } ), true )

res = explode( "a  +b c", " +" )
t( same( res, { "a ", "b c" } ), true )

res = explode( "a;b;c", "/" )
t( same( { "a;b;c" }, explode( "a;b;c", "/" ) ), true )

t()

Inspired by

See also