Problem: I have a string like such:
"this is a !a joke !/a! haha"
The problem is that I want to replace the part "!a joke !/a!"
However, the problem is that I cannot use string.replace() since the part between "!a and !/a!"
changes so sometimes it may be "!a happy !/a!"
or sometimes it may be "!a cheer !/a!"
and so on.... My question is how can I replace this string if all that stays the same is !a
and !/a
You can use string.gsub
with lua string-patterns:
string.gsub("this is a !a joke !/a! haha", "!a %a+ !/a!", "cheer")
If need be you can even capture the string that's between !a
:
local str = "this is a !a joke !/a! haha"
str:gsub ("!a (%a+) !/a!", "sad %1")
Which after substitution gives you "this is a sad joke haha"
.
See the Lua reference manual 6.4.1 - Patterns for other patterns and character classes available.