fix(gears: string: split): support more delimiters (#2962)
This commit is contained in:
parent
65512b5ea9
commit
37aa23be86
|
@ -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
|
||||||
|
|
||||||
|
|
|
@ -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)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue