Skip to content

Instantly share code, notes, and snippets.

@VADemon
Last active April 17, 2024 04:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VADemon/afb10dbb0d10d99aeb21449752da6285 to your computer and use it in GitHub Desktop.
Save VADemon/afb10dbb0d10d99aeb21449752da6285 to your computer and use it in GitHub Desktop.
Plain-text string.replace for Lua (string.gsub without patterns)
-- USAGE:
-- string.replace("mystring", "my", "our")
-- or
-- local teststr = "weird[]str%ing"
-- teststr2 = teststr:replace("weird[]", "cool(%1)")
-- Warning: add your own \0 char handling if you need it!
do
local function regexEscape(str)
return str:gsub("[%(%)%.%%%+%-%*%?%[%^%$%]]", "%%%1")
end
-- you can use return and set your own name if you do require() or dofile()
-- like this: str_replace = require("string-replace")
-- return function (str, this, that) -- modify the line below for the above to work
string.replace = function (str, this, that)
return str:gsub(regexEscape(this), that:gsub("%%", "%%%%")) -- only % needs to be escaped for 'that'
end
end
@mcg1969
Copy link

mcg1969 commented Feb 17, 2024

Thank you for this! I didn't need the "%%" -> "%%%%" replacement but I sure needed the first.

@VADemon
Copy link
Author

VADemon commented Apr 17, 2024

@mcg1969 Thanks mcg, I am glad this snippet found its user :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment