Splitting Strings Based On <> and </>

How would I be able to format a string into a table based on <> and </>. For example:

local message = "Hello this is a <boom>boom effect</boom> and this is a <float>float effect</float>"

into

local MessageTable = {
     "Hello this is a ",
     "<boom>boom effect</boom>",
     " and this is a ",
     "<float>float effect</float>"
}

and then further, remove the <> and </> (for after i get the phrase from the table)

This can be done with pattern matching string. Im not super familiar so there might be better ways.
You can read more about it here: String Patterns

This script assumes text inside <> will contain only characters and the text inbetween two <> * </> only contains characters and white space.

local message: string = "Hello this is a <boom>boom effect</boom> and this is a <float>float effect</float>"

-- Extract <> </>
local matches: {string} = {}
for a, _ in message:gmatch("<%w*>[%w%s]*</%w*>") do
	table.insert(matches, a)
end

local list: {string} = {}
local index = 1
for _, m in ipairs(matches) do
	local a, b = message:find(m)
	
	-- Get normal text and trim
	local normal =  message:sub(index, a-1):gsub("^%s*(.-)%s*$", "%1")
       
       -- Use this line if you dont want to remove white space from start and end of string
       --local normal =  message:sub(index, a-1)
	
	-- Make sure its not empty
	if normal ~= "" then
		table.insert(list, normal)
	end
	table.insert(list, m)
	index = b+1
end

-- Extracted string list
print(list)


-- Remove angle brackets
local newList: {string} = {}
for _, s in ipairs(list) do
	local new = s:gsub("<%w*>", ""):gsub("</%w*>", "")
	table.insert(newList, new)
end

print(newList)
1 Like