Split a string using string.gmatch() in Lua

Niccolo M. picture Niccolo M. · Nov 11, 2013 · Viewed 35.7k times · Source

There are some discussions here, and utility functions, for splitting strings, but I need an ad-hoc one-liner for a very simple task.

I have the following string:

local s = "one;two;;four"

And I want to split it on ";". I want, eventually, go get { "one", "two", "", "four" } in return.

So I tried to do:

local s = "one;two;;four"

local words = {}
for w in s:gmatch("([^;]*)") do table.insert(words, w) end

But the result (the words table) is { "one", "", "two", "", "", "four", "" }. That's certainly not what I want.

Now, as I remarked, there are some discussions here on splitting strings, but they have "lengthy" functions in them and I need something succinct. I need this code for a program where I show the merit of Lua, and if I add a lengthy function to do something so trivial it would go against me.

Answer

Yu Hao picture Yu Hao · Nov 11, 2013
local s = "one;two;;four"
local words = {}
for w in (s .. ";"):gmatch("([^;]*);") do 
    table.insert(words, w) 
end

By adding one extra ; at the end of the string, the string now becomes "one;two;;four;", everything you want to capture can use the pattern "([^;]*);" to match: anything not ; followed by a ;(greedy).

Test:

for n, w in ipairs(words) do
    print(n .. ": " .. w)
end

Output:

1: one
2: two
3:
4: four