Skip to content

Commit

Permalink
feat(stringx) count option for overlap (#326)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tieske authored Jul 30, 2020
1 parent 5013ac3 commit eb4147a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@
### Changes

- `pretty.write`: now also sorts non-string keys [#319](https://github.com/Tieske/Penlight/pull/319)
- `stringx.count` has an extra option to allow overlapping matches
[#326](https://github.com/Tieske/Penlight/pull/326)

### Fixes

- Fix: `stringx.rfind` now properly works with overlapping matches
[#314](https://github.com/Tieske/Penlight/pull/314)

## 1.7.0 (2019-10-14)

Expand Down
8 changes: 6 additions & 2 deletions lua/pl/stringx.lua
Original file line number Diff line number Diff line change
Expand Up @@ -279,9 +279,13 @@ end
--- count all instances of substring in string.
-- @string s the string
-- @string sub substring
function stringx.count(s,sub)
-- @bool[opt] allow_overlap allow matches to overlap
-- @usage
-- assert(stringx.count('banana', 'ana') == 1)
-- assert(stringx.count('banana', 'ana', true) == 2)
function stringx.count(s,sub,allow_overlap)
assert_string(1,s)
local _,k = _find_all(s,sub,1,false,false)
local _,k = _find_all(s,sub,1,false,allow_overlap)
return k
end

Expand Down
3 changes: 3 additions & 0 deletions tests/test-stringx.lua
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,9 @@ asserteq(T(stringx.count('', '')), T(0)) --infinite loop]]
asserteq(T(stringx.count(' ', '')), T(2)) --infinite loop]]
asserteq(T(stringx.count('a..c', '.')), T(2)) -- pattern chars
asserteq(T(stringx.count('a1c', '%d')), T(0)) -- pattern chars
asserteq(T(stringx.count('Anna Anna Anna', 'Anna')), T(3)) -- no overlap
asserteq(T(stringx.count('banana', 'ana', false)), T(1)) -- no overlap
asserteq(T(stringx.count('banana', 'ana', true)), T(2)) -- overlap

-- ljust
asserteq(T(stringx.ljust('', 0)), T(''))
Expand Down

0 comments on commit eb4147a

Please sign in to comment.