Split string with specified delimiter in lua

I am trying to create a split () function in lua with a separator of choice, when the default is space. works fine by default. The problem starts when I give a function separator. For some reason, it does not return the last substring. Function:

function split(str,sep)
if sep == nil then
    words = {}
    for word in str:gmatch("%w+") do table.insert(words, word) end
    return words
end
return {str:match((str:gsub("[^"..sep.."]*"..sep, "([^"..sep.."]*)"..sep)))} -- BUG!! doesnt return last value
end

I am trying to run this:

local str = "a,b,c,d,e,f,g"
local sep = ","
t = split(str,sep)
for i,j in ipairs(t) do
    print(i,j)
end

and I get:

1   a
2   b
3   c
4   d
5   e
6   f

I can’t understand where the error is ...

+4
source share
3 answers

When breaking lines, the easiest way to avoid corner cases is to add a separator to the line when you know that the line cannot end with a separator:

str = "a,b,c,d,e,f,g"
str = str .. ','
for w in str:gmatch("(.-),") do print(w) end

Alternatively, you can use a template with an extra separator:

str = "a,b,c,d,e,f,g"
for w in str:gmatch("([^,]+),?") do print(w) end

, -:

str = "a,b,c,d,e,f,g"
for w in str:gmatch("([^,]+)") do print(w) end
+4

split, "" :

function split(s, sep)
    local fields = {}

    local sep = sep or " "
    local pattern = string.format("([^%s]+)", sep)
    string.gsub(s, pattern, function(c) fields[#fields + 1] = c end)

    return fields
end

t = split("a,b,c,d,e,f,g",",")
for i,j in pairs(t) do
    print(i,j)
end
0

"[^"..sep.."]*"..sep . , , . , (g), .

- \0 ("[^"..sep.."\0]*"..sep), / . , g, , .

, ; , ; -, for -loop gmatch

local result = {}
for field in your_string:gsub(("[^%s]+"):format(your_separator)) do
  table.insert(result, field)
end
return result

EDIT: :

local pattern = "[^%" .. your_separator .. "]+"
for field in string.gsub(your_string, pattern) do
-- ...and so on (The rest should be easy enough to understand)

EDIT2: Keep in mind that you should also avoid your delimiters. A type separator %can cause problems if you do not escape it as%%

function escape(str)
  return str:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
end
0
source

Source: https://habr.com/ru/post/1658301/


All Articles