How to use :split with multiple delimiters?

MyVar = 'a.b,c'
Var = MyVar:split('.')
print(Var)

will print:

[1] = "a",
[2] = "b,c"

I need to split with both . and , delimiters to get:

[1] = "a",
[2] = "b"
[3] = "c"

How can I do that?

1 Like

Done (based on How do I split a string with multiple separators in lua? - Stack Overflow):

function Split_Multi(String, Delim)
	local Table = {}
	local p = "[^"..table.concat(Delim).."]+"
	for Word in String:gmatch(p) do
		table.insert(Table, Word)
	end	
	return Table
end

local Delim = {",", " ", "."}
local String = "a, b c .d e , f 10, M10 , 20,5"

a = Split_Multi(String, Delim)
print(a)
▼  {
    [1] = "a",
    [2] = "b",
    [3] = "c",
    [4] = "d",
    [5] = "e",
    [6] = "f",
    [7] = "10",
    [8] = "M10",
    [9] = "20",
    [10] = "5"
}
2 Likes

You can use %P (the reverse of %p, which detects and punctuation characters), in conjunction with gmatch to retrieve instances of non-punctuation characters.

local str = "a.b,c"

local matches = str:gmatch("%P+")
--[[
    we also have a "+" character so it retrieves continuous
    non-punctuation characters
]]

print(matches) --> notice this is a function and not a table
for result in matches do --> 
    print(result) --> a, b, c
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.