开发者

Lua: Escaping literal % inside string.gsub and the capture %2

开发者 https://www.devze.com 2023-03-31 06:39 出处:网络
Basic question but I\'ve been trying to figure out for a while with no luck. I am processing urls and need to do a simple replacement.

Basic question but I've been trying to figure out for a while with no luck.

I am processing urls and need to do a simple replacement.

I need to replace spaces 开发者_JAVA百科with the literal string %20, but I can't seem to escape the % or the %2 which is reported as an invalid capture.

text = string.gsub(text, "%s+", '%%20')

How many % do I have to use inside gsub to escape the % sign and the %2 capture.


Seems to work for me:

> text="hello world"
> print(string.gsub(text, "%s+", '%%20'))
hello%20world   1

You'll need to show some more code and your error message.


Alternatively, you can automatically do that with the following:

url = require("socket.url")
text = url.escape(string)

This is, of course, assuming you do have the socket library in your lua path. To be quite honest, this is the way I would go about doing anything with urls, because then you don't have to worry about converting commas into %2c or apostrophes into %27.

0

精彩评论

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