This page documents a user-defined function that you can copy and paste into your addon. Replace PREFIX with your addon or lib prefix to avoid conflicts between different versions of these functions.

User defined functions

Return how many times needle is contained in haystack.

number = <PREFIX>_CountChars(haystack, needle)

Function Parameters[edit | edit source]

Arguments[edit | edit source]

String - The search subject.
The string to look for. needle can be a regular expression ('[a-z%s%d]' will count all alphanumeric characters and white spaces)
Arguments are cast into strings before any processing is done.
The search is not case-sensitive.

Returns[edit | edit source]

Number of times needle is contained in haystack. If needle is not found, returns 0.

Example[edit | edit source]

number1 = <PREFIX>_CountChars("World of Warcraft", 'o')
number2 = <PREFIX>_CountChars("World of Warcraft", 'w[a-z]')
number3 = <PREFIX>_CountChars("World of Warcraft", 'r[a-z]')
number4 = <PREFIX>_CountChars("World of Warcraft", 'r[a-z][a-z]')

Result[edit | edit source]

number1 = 2
number2 = 2
number3 = 3
number4 = 3

Code[edit | edit source]

function <PREFIX>_CountChars (haystack, needle)
    haystack = strlower(tostring(haystack));
    needle = strlower(tostring(needle));
    local ret, pos = 0, 0
    for i = 1, strlen(haystack) do
        local s, e = strfind(haystack, needle, pos)
        if e then
            pos = e
            if s == e then
                pos = pos + 1
        if s and e then
            ret = ret + 1;
            break -- If it hasn't found any more, there's no reason to continue
    return ret
Community content is available under CC-BY-SA unless otherwise noted.