Replacing String

  1. What do you want to achieve?

I have a string which I want to replace the specific characters and symbols with nothing: print(“hg[x]llo world”). Replace the g[x] with nothing so it becomes print(“hello world”)

  1. What solutions have I tried so far?
local str = [[
print("hg[x]llo world")
local removeStringValue = string.gsub(str, ("g[x]"), "")

and also looking on google for some results. I do know about string patterns but since I only want to remove the “g[x]” part, removing the square brackets wont help if I have a different string such as running through i. e.g:

names[i] --  will remove the [] becoming "namesi" which I dont want

What was wrong with your solution? This post was pretty confusing, so I’m not really sure what your issue is.


so I summary, I am creating an obfuscator which crypts and decrypts code. Say If I paste code such as:

table = {"cheese", "pickle","sandwitch"}

say if I encryped that code to:

tphblg[x] = {"chg[x]g[x]sg[x]", "pwrvcklg[x]","sphndwwrvtch"}

now the encrypting I coded myself and makes it confusing to read the code. I can decrypt it to:

tablg[x] = {"chg[x]g[x]sg[x]", "picflg[x]","sandwitch"}

now I want to remove the “g[x]” and replace with “e”

Why can’t you just do str:gsub("g[x]", "e")

Do you mean

string.gsub(str,"g[x]", "e")? --because that doesnt work either

that is my issue that (str,“g[”,“e”) throws an error - because brackets

I believe that if you want to detect the g[x] from a string, you’d have to use string:match("g[x]")
Try to do that and tell us if it works.


tablg[x] = {"chg[x]g[x]sg[x]", "picflg[x]","sandwitch"}
local new = tablg[x][1]
local matching = new:match("g[x]")
if matching then

I do want to detect that yes but also replace it from a string - in answer to your response:

if matching then
  remove from str

Forget what I said earlier, I was confused with your question and someone else’s, this should work:

local tablg= {"chg[x]g[x]sg[x]", "picflg[x]","sandwitch"}
local new = tablg[1]
print(string.gsub(new, ("g%[x%]"), ""))

the % will help us detect every g[x] we have in our string.

1 Like

Add a % before the brackets

string.gsub(str, ("g%[x%]"), "")

You need to add a % before every character that is already “in use” in the Lua language, like [] () {} <> and so on


say if I said this:

str = print("hg[x]llo world")

local removeStringValue = string.gsub(str, ("g[x]"), "") -- to make it print("hello world"). I just want to remove the "g[x]" (string).

This way of removing does not work.

Also, worth taking a look here

Thank you all for helping me, @WoTrox has found the issue.