lua gsub特殊替换产生无效的捕获索引
我有一段lua代码(在Corona中执行):
local loginstr = "emailAddress={email} password={password}"
print(loginstr:gsub( "{email}", "[email protected]" ))
此代码生成错误:
无效的捕获索引
虽然我现在知道这是因为在gsub模式中没有正确指定大括号,但我不知道如何修复它。
我应该如何形成 gsub 模式,以便可以用电子邮件地址值替换占位符字符串?
我浏览了所有我能找到的面向 lua 的网站,但大多数文档似乎都是围绕不相关的情况展开的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如我在上面的评论中所建议的,当电子邮件被编码为 URL 参数时,用于编码“@”字符的 %40 将用作捕获索引。由于搜索模式没有任何捕获(更不用说 40 个捕获),这将导致问题。
有两种可能的解决方案:您可以对编码的字符串进行解码,或者对替换字符串进行编码以转义其中的“%”字符。根据您要对最终结果执行的操作,您可能需要同时执行这两项操作。
以下例程(我从此处获取 - 未测试)可以解码编码字符串:
用于转义字符串中的 % 字符
str
,您可以使用:'%' 字符被转义为 '%%',并且需要在搜索模式和替换模式上进行转义(因此 % 字符的数量代替)。
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:
For escaping the % character in string
str
, you can use: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).
您确定问题不是您尝试在
loginurl
上使用gsub
而不是loginstr
吗?您的代码给了我这个错误(请参阅 http://ideone.com/wwiZk):
这听起来类似于你看到了。只需修复它以使用正确的变量:
说(参见 http://ideone.com/mMj0N):
根据需要。
Are you sure your problem isn't that you're trying to
gsub
onloginurl
rather thanloginstr
?Your code gives me this error (see http://ideone.com/wwiZk):
and that sounds similar to what you're seeing. Just fixing it to use the right variable:
says (see http://ideone.com/mMj0N):
as desired.
我在 value 部分中有这个,所以你需要使用:value:gsub("%%", "%%%%") 来转义值。
替换 json 中“某些值”的示例:
I had this in value part so You need to escape value with: value:gsub("%%", "%%%%").
Example of replacing "some value" in json: