fix(gears: string: split): support more delimiters (#2962)

This commit is contained in:
Yauhen Kirylau 2020-01-20 01:04:28 +01:00 committed by Emmanuel Lepage Vallée
parent 65512b5ea9
commit 37aa23be86
2 changed files with 17 additions and 8 deletions

View File

@ -93,16 +93,19 @@ end
-- @treturn table list of the substrings
-- @staticfct gears.string.split
function gstring.split(str, delimiter)
local pattern = "(.-)" .. delimiter .. "()"
delimiter = delimiter or "\n"
local result = {}
local n = 0
local lastPos = 0
for part, pos in string.gmatch(str, pattern) do
n = n + 1
result[n] = part
lastPos = pos
if gstring.startswith(str, delimiter) then
result[#result+1] = ""
end
local pattern = string.format("([^%s]+)", delimiter)
str:gsub(pattern, function(c) result[#result+1] = c end)
if gstring.endswith(str, delimiter) then
result[#result+1] = ""
end
if #result == 0 then
result[#result+1] = str
end
result[n + 1] = string.sub(str, lastPos)
return result
end

View File

@ -48,6 +48,12 @@ describe("gears.string", function()
assert.is_same(gstring.split("foo", "\n"), {"foo"})
assert.is_same(gstring.split("foo\n", "\n"), {"foo", ""})
assert.is_same(gstring.split("foo\nbar", "\n"), {"foo", "bar"})
assert.is_same(gstring.split("", "."), {""})
assert.is_same(gstring.split(".", "."), {"", ""})
assert.is_same(gstring.split("foo", "."), {"foo"})
assert.is_same(gstring.split("foo.", "."), {"foo", ""})
assert.is_same(gstring.split("foo.bar", "."), {"foo", "bar"})
end)
end)