English I need a replace function.

2 replies
Goto Page
To the start Previous 1 Next To the start
13.04.19 09:03:20 pm
Up
Goo
User
Offline Off
Hi! I don't really like the gsub function in Lua and was wondering if anyone has (or can make) an easier function for me that will do the following:

INPUT:
Code:
1
2
3
local str = 'a b c'
str = replace(str, ' b ', ' d ')
print(str)

OUTPUT:
Code:
1
a d c


Thanks!
14.04.19 02:28:51 am
Up
panteon00
User
Offline Off
but isn't it exactly what gsub does?
it is already the syntax you want

anyway, here is your code:
Code:
1
2
3
function replace(str, pattern, rep)
     return string.gsub(str, pattern, rep)
end
loading...
15.04.19 12:16:08 am
Up
VADemon
User
Offline Off
I don't know why you don't like gsub... okay.
string.gsub also accepts magical regular expression patterns, so there's a little more to it if you only want to replace normal text:
https://gist.github.com/VADemon/afb10dbb0d10d99aeb21449752da6285

Code:
1
2
3
4
5
6
7
8
9
do
     local function regexEscape(str)
          return str:gsub("[%(%)%.%%%+%-%*%?%[%^%$%]]", "%%%1")
     end

     string.replace = function (str, this, that)
          return str:gsub(regexEscape(this), that:gsub("%%", "%%%%")) -- only % needs to be escaped for 'that'
     end
end


The regexEscape escapes all magic characters that gsub understands (yes it's a clusterfuck of a pattern, but if you try to do it yourself, it'll make sense).
So 'this' is escaped. But 'that' also needs to be escaped, it understands "%0", "%1..."%9" as stuff to replace from the previously captured string. "%%%%" Does exactly that, transforms single "%" to "%%" so they're no longer an issue.

Quote:
-- USAGE:
-- string.replace("mystring", "my", "our")
-- or
-- local teststr = "weird[]str%ing"
-- teststr2 = teststr:replace("weird[]", "cool(%1)")
To the start Previous 1 Next To the start