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:
Just changing * to + works.
local s = "one;two;;four"
local words = {}
for w in s:gmatch("([^;]+)") do
table.insert(words, w)
print(w)
end
The magic character * represents 0 or more occurrene, so when it meet ',', lua regarded it as a empty string that [^;] does not exist.
function split(str,sep)
local array = {}
local reg = string.format("([^%s]+)",sep)
for mem in string.gmatch(str,reg) do
table.insert(array, mem)
end
return array
end
local s = "one;two;;four"
local array = split(s,";")
for n, w in ipairs(array) do
print(n .. ": " .. w)
end
result:
1:one
2:two
3:four
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