Lua用函数替换字符串



我想用一些函数替换匹配的字符串。

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

打印(文本(显示%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中使用匹配字符串?

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

但是,来自gsub文档的以下信息告诉我们,您可以将replace_function直接传递给gsub:

如果repl是一个函数,则每次发生匹配时都会调用此函数,并按顺序将所有捕获的子字符串作为参数传递。

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

最新更新