3

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Do closing bracket ], percent % and dash - allowed to be among user-defined delimiters?
I normally use this function to avoid such problems: function escape_magic(s) local MAGIC_CHARS_SET = '[()%%.[^$%]*+%-?]' if s == nil then return end return (s:gsub(MAGIC_CHARS_SET,'%%%1')) end
@tonypdmtr - Why not simply (s:gsub("%p", "%%%0")) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.