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( "taptest" )
local countmatch = require( "countmatch" )

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

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

t()

Inspired by