Search code examples
regexluareplacegsub

lua gsub special replacement producing invalid capture index


I have a piece of lua code (executing in Corona):

local loginstr = "emailAddress={email} password={password}"
print(loginstr:gsub( "{email}", "[email protected]" ))

This code generates the error:

invalid capture index

While I now know it is because of the curly braces not being specified appropriately in the gsub pattern, I don't know how to fix it.

How should I form the gsub pattern so that I can replace the placeholder string with the email address value?

I've looked around on all the lua-oriented sites I can find but most of the documentation seems to revolve around unassociated situations.


Solution

  • As I've suggested in the comments above, when the e-mail is encoded as a URL parameter, the %40 used to encode the '@' character will be used as a capture index. Since the search pattern doesn't have any captures (let alone 40 of them), this will cause a problem.

    There are two possible solutions: you can either decode the encoded string, or encode your replacement string to escape the '%' character in it. Depending on what you are going to do with the end result, you may need to do both.

    the following routine (I picked up from here - not tested) can decode an encoded string:

    function url_decode(str)
      str = string.gsub (str, "+", " ")
      str = string.gsub (str, "%%(%x%x)",
          function(h) return string.char(tonumber(h,16)) end)
      str = string.gsub (str, "\r\n", "\n")
      return str
    end
    

    For escaping the % character in string str, you can use:

    str:gsub("%%", "%%%%")
    

    The '%' character is escaped as '%%', and it needs to be ascaped on both the search pattern and the replace pattern (hence the amount of % characters in the replace).