68

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)

1
  • 6
    Because ^ is a special character, you need use % to escape it in Lua. Commented Nov 30, 2010 at 2:03

1 Answer 1

113

Try:

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

The tutorial uses a slightly different syntax. Why is gsub written with a : instead of a . in this answer?
@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.
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 %2b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.