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