1

I want to replace matched string with some function.

I've used '%1' to find strings, but I couldn't use the matched strings.

print(text) showed me %1, not matched string.

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)

How can I use matched string in gsub?

1 Answer 1

2

The problem is that replace_function gets called before gsub can start running. replace_function doesn't know what %1 means, and it doesn't return a string that has any special meaning to gsub.

However, the following information from the gsub doc tells us that you can pass replace_function directly to gsub:

If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order.

original_text:gsub("${(.-)}", replace_function)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.