String.gsub function doesn't work with certain string

I am making an admin system where I put “[PRE]” into the example column for each command, so that the admin GUI can automatically fill it in with the prefix followed by the name of the command. I do this using string.gsub.

However, instead of turning [PRE] into ;commandname, it turns it into [;commandname;commandname;commandname].

To test this, I ran the following test code in the command bar:

print(string.gsub("[PRE] dog","[PRE]","frog"))

And got the output [frogfrogfrog] dog 3

However, when I tested it with this code (without one of the brackets)…

print(string.gsub("[PRE] dog","PRE]","frog"))

I got [frog dog 1 returned in the output menu.

As I was writing this, I noticed that if I keep the FIRST bracket instead of the second, I get the following error:

What is going on with my string manipulation?

Brackets mean something special in String Patterns.

Magic Characters

There are 12 “magic characters” which are reserved for special purposes in patterns:

$ % ^ * ( )
. [ ] + - ?

Instead of using their special meaning, you can precede them with a % symbol to search for them literally. This is called character escaping . For example, to search for , you’ll need to escape the . (period) symbol by preceding it with a % .

So use

print(string.gsub("[PRE] dog","%[PRE%]","frog"))
1 Like