How do I make string.gsub() work with patterns such as {PlayerMoney}?

Hi. I’m trying to figure out how to make string.gsub detect and replace patterns such as {PlayerMoney}, {EnemyCount}, {Faction}, basically any token wrapped in curly brackets. I’d like to do this to make my unformatted strings a little bit easier to understand, but I just can’t figure out how to get it to work.

I’ve experimented with several different string patters, using stuff like %w+, [%w%p]+, [%w%{%}]+, and I even used period (.) to try to detect all characters, to no avail.

How can I do what I’m trying to do? Any help would be greatly appreciated!

2 Likes

Also tried [%w%{}]+, no dice there either.

You may be looking for "%b{}"! This matches the curly brackets and the content inside.

function token(t: string)
    if t == "{name}" then
        return "Bob"
    elseif t == "{money}" then
        return 100
    end
end

print( string.gsub("{name} has {money}$!","%b{}",token) )
output: --Bob has 100$!
2 Likes

I think you might be looking for string interpolation.

local values = {
	Foo = "Bar",
	Hello = "World",
	Test123 = "Success"
}

local str = "Say {Hello}, run {Test123}, value is {Foo}, keep {Unknown}"
str = str:gsub("{(.-)}", function(k) return values[k] or "{"..k.."}" end)

print(str)

Output: Say World, run Success, value is Bar, keep {Unknown}

Wow, that actually worked really well! Thank you so much!

1 Like