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
|
||||
-- @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
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
Loading…
Reference in New Issue