How to find and replace multiple substrings in a string

Hello! I am trying to create a module script that:

  1. finds 1 or more substring(s) from a given string
  2. replaces the substring(s) with a different substring for each one
  3. returns the modified string, so I can use it on other scripts.

However, I am a bit stuck on it, so can anyone tell me how to fix it?

Here is the code:

local module = {
	["Dictionary"] = {
		["Cat"] = {
			"Ice Cream",
			"Cookie",
			"Cake"
		["Dog"] = {
			"Pizza",
			"Hamburger",
			"Taco"
		}
	}
}

function lower(str)
	return str:lower()
end

function random(min, max)
	return math.random(min, max)
end

function module:ReplaceWords(givenString)
	local loweredString = lower(givenString)

	if loweredString:find("cat") then
		local cat = module.Dictionary.Cat

		local newString1 = string.gsub(loweredString, "cat", cat[random(1, #cat)

		if loweredString:find("dog") then
			local dog = module.Dictionary.Dog
			
			local newString2 = string.gsub(loweredString, "dog", dog[random(1, #dog)

			return newString2

		else

			return newString1

		end

	else

		return loweredString

	end

end

return module

please help

You can use the gsub function on strings to run functions on patterns within the strings.

Patterns here: Programming in Lua : 20.2


local string = "I think the sky is blue, just blue."

function replaceFn(word)
    if word == "blue" then
        return "red"
    else
        return word
    end
end

local replacedString = string:gsub("%a+", replaceFn)

print(replacedString)

so im guessing this iterates through each word of the string?

Yes. Other useful patterns are ‘.’ for every character and ‘%d+’ for every number. To iterate over a word, ‘%a’ looks for a letter, and ‘+’ lets it look for multiple letters next to each other.

i used this for my script and it worked so thank you

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.