Reine Elemente
Reine Elemente

Reputation: 131

How do I split a string with multiple separators in lua?

I want to split a string into an array divided by multiple delimiters.

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

Result table should look like this:

{"a", "b", "c", "d", "e",  "f", "10", "M10", "20", "5"}

Delimiters can be white spaces, commas or dots. If two delimiters like a white space and comma are coming after each other, they should be collapsed, additional whitespaces should be ignored.

Upvotes: 3

Views: 1717

Answers (1)

lhf
lhf

Reputation: 72412

This code splits the string as required by building a pattern of the complement of the delimiter set.

local delim = {",", " ", "."}
local s = "a, b c .d e , f 10, M10 , 20,5"
local p = "[^"..table.concat(delim).."]+"
for w in s:gmatch(p) do
        print(w)
end

Adapt the code to save the "words" in a table.

Upvotes: 5

Related Questions