Find a keyword in a string and how many times it repeats

Title. How do you go about achieving this?

I know :find achieves a similar result, but it does not tell me how many times the keyword repeats itself in the string.

2 Likes

repeat string.find or :find and instead change the init:

local text = "I love tacos, tacos are my favourite!"
local patern = "taco"
local init = 1
local result1, result2 = string.find(text,  patern, init)

every time you get results you check for the next one (just do init += 1)

for :find() use:

local result1, result2 = text:find(patern, init)

Here are some ways I found:

  • Using gmatch
local function countSubstring(text, keyword)
	local count = 0
	
	for _ in text:gmatch(keyword) do
		count += 1
	end

	return count
end
  • Using gsub
local function countSubstring(text, keyword)
	local count = 0

	text:gsub(keyword, function()
		count += 1
	end)

	return count
end
  • Using gsub (a shorter version from a friend)
local function countSubstring(text, keyword)
	return select(2, text:gsub(keyword, ""))
end
  • Without select:
local function countSubstring(text, keyword)
	local _, count = text:gsub(keyword, "")
	return count
end
  • Using find
local function countSubstring(text, keyword)
	local count = 0
	local init
	
	repeat
		_, init = text:find(keyword, init)
		if init then count += 1 end
	until init == nil
	
	return count
end

You can then use the function like so:

print(countSubstring("I love tacos, tacos are my favourite!", "taco"))
1 Like

you can simply do this instead for gsub

local function countSubstring(text, keyword)
	local _, count = text:gsub(keyword, "")

	return count
end

print(countSubstring("I love tacos, tacos are my favourite!", "taco"))
3 Likes

How do I make it search for two or more keywords?
Thanks btw

Use the gmatch() function to achieve this.

http://lua-users.org/wiki/StringLibraryTutorial

local function countSubstring(text, keywords)
    local count = {}

    for _, keyword in ipairs(keywords) do
        count[keyword] = select(2, text:gsub(keyword, ""))
    end

    return count
end

print(countSubstring("abc def def", {"abc", "def"}))

OUTPUT

{
    abc = 1,
    def = 2
}

not sure if this is exactly what you want, but I hope it helps