Very confusing errors when trying to use string.gsub

I’m terrible when it comes to figuring out string patterns. Today I decided I would try to make a gui similar to the dev console. Easy enough. The only problem is highlighting the text just like the script editor. The method I came up with was to use rich text and use string.gsub to replace the keywords.

I keep getting this error:
ScriptGui.TextHighlighter:63: invalid capture index %1

I genuinley have no clue what it means. Could someone point me in the right direction when it comes to this stuff?

The error happens on this line btw:

if string.match(TextBox.Text, "%"..Keyword) then
Full Script:
local Terms = {
	["StringCharacters"] = {"'",'"'},
	["MathStuff"] = {"1","2","3","4","5","6","7","8","9","0","+","-","*","^",".","%","[","]","{","}",":",";","=","!","~","(",")",","},
	["Globals"] = {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"}
}

local function HighlightTextbox(TextBox)
	for KeywordType, KeywordTable in pairs(Terms) do
		for _,Keyword in pairs(KeywordTable) do
			if string.match(TextBox.Text, "%"..Keyword) then
				
				-- The error happens here :(
				
			end
		end
	end
	

The % designates capture groups.

It’s meant to tell the code what to look for in a string. If you designate a weird capture group, it won’t like that.

%1 is probably a weird capture group for it, as it searches your terms lists.

Why are you using the % sign? It’s meant for %l(letters) or %d(numbers) or other capture group designations. If you force it to look for things like %1, it’ll tell you that that’s not a valid capture group, like it is.

1 Like

You only need to escape the following characters:
+, -, *, ^, ., %, (, ), [, ]

You can manually do this by saying
"%+","%-","%*" ...
Rather than putting it in the loop

1 Like

I didn’t even think of that. I will try that now.

It works! I have marked your reply as a solution :grin: