lemonowo
lemonowo

Reputation: 45

regex for matching a string into words but leaving multiple spaces

Here's what I expect. I have a string with numbers that need to be changed into letters (a kind of cipher) and spaces to move into different letter, and there is a tripple spaces that represent a space in output. For example, a string "394 29 44 44 141 6" will be decrypted into "Hell No".

function string.decrypt(self)
    local output = ""

    for i in self:gmatch("%S+") do
        for j, k in pairs(CODE) do
            output = output .. (i == j and k or "")
        end
    end

    return output
end

Even though it decrypts the numbers correctly I doesn't work with spacebars. So the string I used above decrypts into "HellNo", instead of expected "Hell No". How can I fix this?

Upvotes: 1

Views: 55

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You can use

CODE = {["394"] = "H", ["29"] = "e", ["44"] = "l", ["141"] = "N", ["6"] = "o"}
function replace(match)
    local ret = nil
    for i, v in pairs(CODE) do
        if i == match then
            ret = v
        end
    end
    return ret
end

function decrypt(s)
    return s:gsub("(%d+)%s?", replace):gsub("  ", " ")
end

print (decrypt("394 29 44 44   141 6"))

Output will contain Hell No. See the Lua demo online.

Here, (%d+)%s? in s:gsub("(%d+)%s?", replace) matches and captures one or more digits and just matches an optional whitespace (with %s?) and the captured value is passed to the replace function, where it is mapped to the char value in CODE. Then, all double spaces are replaced with a single space with gsub(" ", " ").

Upvotes: 1

Related Questions