diff --git a/lib/gears/string.lua b/lib/gears/string.lua index 159981ed..973db01c 100644 --- a/lib/gears/string.lua +++ b/lib/gears/string.lua @@ -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 diff --git a/spec/gears/string_spec.lua b/spec/gears/string_spec.lua index 58f0396e..a696cbb2 100644 --- a/spec/gears/string_spec.lua +++ b/spec/gears/string_spec.lua @@ -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)