How to split a string in Lua programming?


Splitting a string is the process in which we pass a regular expression or pattern with which one can split a given string into different parts.

In Lua, there is no split function that is present inside the standard library but we can make use of other functions to do the work that normally a split function would do.

A very simple example of a split function in Lua is to make use of the gmatch() function and then pass a pattern which we want to separate the string upon.

Example

Consider the example shown below −

 Live Demo

local example = "lua is great"
for i in string.gmatch(example, "%S+") do
   print(i)
end

Output

lua
is
great

The above example works fine for simple patterns but when we want to make use of a regular expression and the case that we can have a default pattern with which to split, we can consider a more elegant example.

Example

Consider the example shown below −

 Live Demo

function mysplit (inputstr, sep)
   if sep == nil then
      sep = "%s"
   end
   local t={}
   for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
      table.insert(t, str)
   end
   return t
end
ans = mysplit("hey bro whats up?")
for _, v in ipairs(ans) do print(v) end
ans = mysplit("x,y,z,m,n",",")
for _, v in ipairs(ans) do print(v) end

Output

hey
bro
whats
up?
x
y
z
m
n

Updated on: 20-Jul-2021

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements