Forum

> > CS2D > Scripts > I need a replace function.
Forums overviewCS2D overview Scripts overviewLog in to reply

English I need a replace function.

2 replies
To the start Previous 1 Next To the start

old I need a replace function.

Mami Tomoe
User Off Offline

Quote
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:
1
2
3
local str = 'a b c'
str = replace(str, ' b ', ' d ')
print(str)
OUTPUT:
1
a d c

Thanks!

old Re: I need a replace function.

Cebra
User Off Offline

Quote
but isn't it exactly what gsub does?
it is already the syntax you want

anyway, here is your code:
1
2
3
function replace(str, pattern, rep)
	return string.gsub(str, pattern, rep)
end

old Re: I need a replace function.

VADemon
User Off Offline

Quote
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

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
Log in to reply Scripts overviewCS2D overviewForums overview