Find occurrencies in a String

Hey everyone, thanks for reading!

Im not experienced with manipulating a string only the common required basics, and I cant find how to do this correctly.

How to search in this string and get all “waka(things)” occurrencies in? By things I mean everything that is inside the ( ). Like doing string.match("bla bla waka(stuff "in here" ¿"!"#) ", "%b()"). That would return the stuff inside the (). But, I want to collect from the word “waka” and everything that the () contains merged as one string, like:
local newString = "waka(stuff "in here" ¿"!"#)"

All special characters should be added, so I suppose format the string is required too

local Occurencies = {}

local function EditString(myString)
	local Collected = -- collected waka() stuff
	table.insert(Occurencies, Collected )	
end

local theString = "Once upon a time, a brave knight saved a princess from a dragon. She gave him a waka('mole' cosa, anything) in return, and they lived happily ever after."
EditString(theString)

Any suggestion is appreciated, thank you for reading!

You can use %b it matches a balanced pair of characters like () or [].

local Occurrences = {}
local function EditString(myString)
	for match in myString:gmatch("waka%b()") do
		table.insert(Occurrences, match)
	end
end

local theString = "Once upon a time, a brave knight saved a princess from a dragon. She gave him a waka('mole' cosa, anything) in return, and they lived happily ever after."
EditString(theString)

-- Print the collected occurrences from the table
for i, occurrence in ipairs(Occurrences) do
	print(i, occurrence) 
end
1 Like

By reading it, it looks so obvious haha thank you so much, Im gonna try it right now, makes totally sense so probably it works nicely.

About the string format? makes any difference if the string contains any “special character”?
like () or "",'' '' __, hu

Like when hardcoding a table this could happen:
local thing = 'gnome's hat' -- this would be shown as error in studio
should be local thing = "gnome's hat"

If something like that is saved in the table, would it break? and I should format the string per character to save it safely?