1

How do I split string with whitespaces and numbers in it by comma?

e.g

str = "bar, bar123, bar 123, 123"

to a table containing

{"bar", "bar123", "bar 123", "123"}
DnBs
  • 45
  • 4
  • 1
    Possible duplicate of [Split string in Lua?](https://stackoverflow.com/questions/1426954/split-string-in-lua) – Aki May 16 '19 at 09:44

4 Answers4

2

The key to simplifying pattern matching is to ensure uniformity. In this case, this is achieved by ensuring that every field has a terminating comma:

for w in (str..","):gmatch("(.-),%s*") do
   print("["..w.."]")
end
lhf
  • 70,581
  • 9
  • 108
  • 149
0

Install the split module from luarocks, then

split = require("split").split
t = split(str, ', ')
for _, val in ipairs(t) do print(">" .. val .. "<") end
>bar<
>bar123<
>bar 123<
>123<
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

You can use this function.

function string:split(_sep)
    local sep, fields = _sep or ":", {}
    local pattern = string.format("([^%s]+)", sep)
    self:gsub(pattern, function(c) fields[#fields+1] = c end)
    return fields
end

This will return a table which is split by '_sep'.

OuChenglin
  • 24
  • 2
0

In case someone else is directed here by google looking for a working answer with basic lua:

str_tbl = {}
for value in string.gmatch(str, '([^, *]+)') do
  str_tbl[#str_tbl+1] = value 
end