【问题标题】:Lua replace string with functionLua用函数替换字符串
【发布时间】:2021-07-20 08:25:43
【问题描述】:

我想用某个函数替换匹配的字符串。

我已使用 '%1' 查找字符串,但无法使用匹配的字符串。

print(text) 显示 %1,不匹配的字符串。

original_text = "Replace ${test01} and ${test02}"

function replace_function(text)
    -- Matched texts are "test01" and "test02"
    -- But 'text' was "%1", not "test01" and "test02"
    local result_text = ""

    if(text == "test01") then
        result_text = "a"
    elseif(text == "test02") then
        result_text = "b"
    end

    return result_text
end

replaced_text = original_text:gsub("${(.-)}", replace_function("%1"))

-- Replace result was "Replace  and"
-- But I want to replace "Replace ${test01} and ${test02}" to "Replace a and b"
print(replaced_text)

如何在 gsub 中使用匹配的字符串?

【问题讨论】:

    标签: lua


    【解决方案1】:

    问题是replace_functiongsub 可以开始运行之前被调用。 replace_function 不知道%1 是什么意思,也不会向gsub 返回一个有任何特殊含义的字符串。

    但是,gsub doc 的以下信息告诉我们,您可以将replace_function 直接传递给gsub

    如果repl 是一个函数,那么每次匹配时都会调用这个函数,所有捕获的子字符串作为参数依次传递。

    original_text:gsub("${(.-)}", replace_function)
    

    【讨论】: