I want to turn a string like "hello-world"
into a list of strings: {"hello-", "world"}
I can easily split by hyphens:
local r = {} for word in text:gmatch("[^-]+") do table.insert(r, word) end
and I can approximately put it together by assuming each word was followed by a hyphen:
for i, word in pairs(r) do if i < #r then word[i] = word[i] .. "-" end end
but that is assuming that there is precisely one hyphen after each word and that the string doesn't start or end with hyphens.
I was considering something like this:
local r = {} for word in text:gmatch("%-|[^-]+") do table.insert(r, word) end
but Lua string patterns doesn't have support for "either" (what I wanted by the |
), so that pattern doesn't work.
Is there any way to do this without going character-by-character?
More examples:
"--a--b---c"
--> {"--a--", "b---", "c"}
or {"--", "a--", "b---", "c"}
-- I don't care which
"hello-there-person"
--> {"hello-", "there-", "person"}
"hello"
--> {"hello"}
The string pattern [^-]*-*
will do the trick, sort of. At the end it will always match an empty string (though this could probably be filtered out) with a really simple #
check.
This fulfills the examples given.
-- text = "hello-world" --> "hello-", "world" -- text = "--a--b---c" --> "--", "a--", "b---", "c" -- text = "hello-there-person" --> "hello-", "there-", "person" -- text = "hello" --> "hello" text = "--a--b---c" for word in text:gmatch("[^-]*-*") do if #word > 0 then print(word) end end
While is it true there is no support for either and so %-|[^-]+
would not be possible, you can just sidestep this in this particular case with the *
operator, which matches 0 or more.
The strategy would be to include non-hyphen characters with [^-]*
and include hyphens in the end with -*
.
Edit Ok remembered I can use *, and now my method is great :)
local k = {"hello-world", "--a--b---c", "hello-there-person", "hello"} local listOfStrings = {} for _,d in pairs(k) do d:gsub("(-*[^-]+-*)", function(x) table.insert(listOfStrings, x) end) end