countmatch

function countmatch( str, pattern [, plain] ) --> n

Description

Returns the number of occurrences of the pattern in str. If plain is defined with true no characters in pattern will be considered magic.

Parameters

str

The source string that should be scanned.

pattern

The pattern or substring that should be used.

plain

Defines if plain.

Return Values

n

Number of occurrences of the pattern.

Code

--ZFUNC-countmatch-v1
local function countmatch( str, pattern, plain )
   if #pattern == 0 then return 0 end

   local n = 0
   local i, j = 0, 0
   repeat
      i, j = string.find( str, pattern, j+1, plain )
      if i then n = n+1 end
   until i == nil
   return n
end

return countmatch

Examples

local t = require( "tapered" )
local countmatch = require( "countmatch" )

-- sub string
t.is( 3, countmatch( "aaa", "a" ) )
t.is( 0, countmatch( "", "" ) )
t.is( 0, countmatch( "", "a" ) )

-- use pattern
t.is( 4, countmatch( "hello world from Lua", "%a+" ) ) -- count words

t.done()

Inspired by