Lua String replace
Asked Answered
S

1

66

How would i do this?

I got this:

name = "^aH^ai"
string.gsub(name, "^a", "")

which should return "Hi", but it grabs the caret character as a pattern character

What would be a work around for this? (must be done in gsub)

Shang answered 28/11, 2010 at 16:5 Comment(1)
Because ^ is a special character, you need use % to escape it in Lua.Terrigenous
G
109

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Gamogenesis answered 28/11, 2010 at 16:33 Comment(3)
The tutorial uses a slightly different syntax. Why is gsub written with a : instead of a . in this answer?Galasyn
@AndersonGreen: it can be called as a library function of the string library or as a method on a string object. The : is syntax sugar in Lua which effectively implies the object on which the method is called being passed as first parameter.Crosshatch
What if we want to replace special characters with special character? like email = email:gsub("%+", "%2b"). Effectively we want to to URL Encode the + to %2bMartlet

© 2022 - 2024 — McMap. All rights reserved.