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
2 Likes

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

2 Likes

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

table = {"cheese", "pickle","sandwitch"}
print(table[2])

say if I encryped that code to:

tphblg[x] = {"chg[x]g[x]sg[x]", "pwrvcklg[x]","sphndwwrvtch"}
prwrvnt(tphblg[x][2])

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"}
print(tablg[x][2])

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.

Example:

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
  --code
end

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
end

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

6 Likes

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.

1 Like