开发者

lua gsub special replacement producing invalid capture index

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

local loginstr = "emailAd开发者_JAVA技巧dress={email} password={password}"
print(loginstr:gsub( "{email}", "tester@test.com" ))

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.


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).


Are you sure your problem isn't that you're trying to gsub on loginurl rather than loginstr?

Your code gives me this error (see http://ideone.com/wwiZk):

lua: prog.lua:2: attempt to index global 'loginurl' (a nil value)

and that sounds similar to what you're seeing. Just fixing it to use the right variable:

print(loginstr:gsub( "{email}", "tester@test.com" ))

says (see http://ideone.com/mMj0N):

emailAddress=tester@test.com password={password}

as desired.


I had this in value part so You need to escape value with: value:gsub("%%", "%%%%").

Example of replacing "some value" in json:

local resultJSON = json:gsub(, "\"SOME_VALUE\"", value:gsub("%%", "%%%%"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜