Skip to content

Commit

Permalink
Added gears.string.psplit function to support patterns (#3839)
Browse files Browse the repository at this point in the history
  • Loading branch information
Piterden authored Nov 19, 2023
1 parent 7ed4dd6 commit dfe6a47
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/gears/string.lua
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ function gstring.query_to_pattern(q)
return s
end


--- Split separates a string containing a delimiter into the list of
-- substrings between that delimiter.
-- @tparam string str String to be splitted
Expand All @@ -110,6 +111,33 @@ function gstring.split(str, delimiter)
return result
end


--- Pattern split separates a string by a pattern to the table of substrings.
-- @tparam string str String to be splitted
-- @tparam string[opt="\n"] pattern Pattern the target string will
-- be splitted by.
-- @treturn table A list of substrings.
-- @staticfct gears.string.split
function gstring.psplit(str, pattern)
pattern = pattern or "\n"
local result = {}
if #pattern == 0 then
for index = 1, #str do
result[#result+1] = str:sub(index, index)
end
return result
end
local pos = 1
for match in str:gmatch(pattern) do
local start_pos, end_pos = str:find(match, pos, true)
result[#result+1] = str:sub(pos, start_pos-1)
pos = end_pos+1
end
result[#result+1] = str:sub(pos, #str)
return result
end


--- Check if a string starts with another string.
-- @DOC_text_gears_string_startswith_EXAMPLE@
-- @tparam string str String to search
Expand Down
14 changes: 14 additions & 0 deletions spec/gears/string_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,20 @@ describe("gears.string", function()
assert.is_same(gstring.split("foo.", "."), {"foo", ""})
assert.is_same(gstring.split("foo.bar", "."), {"foo", "bar"})
end)

describe("psplit", function()
assert.is_same(gstring.psplit("", ""), {})
assert.is_same(gstring.psplit(".", ""), {"."})
assert.is_same(gstring.psplit("foo", ""), {"f", "o", "o"})
assert.is_same(gstring.psplit("foo.", ""), {"f", "o", "o", "."})
assert.is_same(gstring.psplit("foo.bar", "%."), {"foo", "bar"})

assert.is_same(gstring.psplit("", "."), {""})
assert.is_same(gstring.psplit("a", "."), {"", ""})
assert.is_same(gstring.psplit("foo", "."), {"", "", "", ""})
assert.is_same(gstring.psplit("foo.", "%W"), {"foo", ""})
assert.is_same(gstring.psplit(".foo.2.5.bar.73", "%.%d"), {".foo", "", ".bar", "3"})
end)
end)

-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80

0 comments on commit dfe6a47

Please sign in to comment.