【问题标题】:I need to fix malformed pattern error我需要修复格式错误的模式错误
【发布时间】:2016-10-12 17:33:56
【问题描述】:

我想用 $ 替换 % 符号。我尝试做一个转义字符 () 但这没有用。我正在使用 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 '%')

【问题讨论】:

    标签: lua gsub


    【解决方案1】:

    你需要转义%并写%%

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

    【讨论】:

    • 感谢您的帮助! :)
    猜你喜欢
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 2012-04-16
    • 2018-04-21
    • 1970-01-01
    相关资源
    最近更新 更多