我想用$替换%符号。我尝试做一个转义字符()但是没有用。我正在使用lua 5.1,我得到一个格式错误的模式错误。 (以'%'结尾)这是困扰我,因为我不知道如何解决它。
io.write("Search: ") search = io.read()
local query = search:gsub("%", "%25") -- Where I put the % sign.
query = query:gsub("+", "%2B")
query = query:gsub(" ","+")
query = query:gsub("/", "%2F")
query = query:gsub("#", "%23")
query = query:gsub("$", "%24")
query = query:gsub("@", "%40")
query = query:gsub("?", "%3F")
query = query:gsub("{", "%7B")
query = query:gsub("}","%7D")
query = query:gsub("[","%5B")
query = query:gsub("]","%5D")
query = query:gsub(">", "%3E")
query = query:gsub("<", "%3C")
local url = "https://www.google.com/#q=" .. query
print(url)
输出读数:
malformed pattern (ends with '%')
答案 0 :(得分:2)
您需要转义%
并撰写%%
。
惯用法在Lua中执行此操作的目的是为gsub
提供一个表格:
local reserved="%+/#$@?{}[]><"
local escape={}
for c in reserved:gmatch(".") do
escape[c]=string.format("%%%02X",c:byte())
end
escape[" "]="+"
query = search:gsub(".", escape)