Last active
January 29, 2025 09:10
-
-
Save VADemon/afb10dbb0d10d99aeb21449752da6285 to your computer and use it in GitHub Desktop.
Plain-text string.replace for Lua (string.gsub without patterns)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this! I didn't need the "%%" -> "%%%%" replacement but I sure needed the first.