LUA |字符串模式替换

问题描述 投票:0回答:2
local str = {
    ["red"] = "ff0000",
    ["blue"] = "4C9FFF",
    ["purple"] = "C33AFF",
    ["green"] = "53FF4A",
    ["gray"] = "E2E2E2",
    ["black"] = "000000",
    ["white"] = "ffffff",
    ["pink"] = "FB8DFF",
    ["orange"] = "FF8E1C",
    ["yellow"] = "FAFF52",
    --TODO Add Colors
}

function str:generate_string(text)
    assert(text and type(text) == "string")

    local function replaceColor(match)
        local colorName = match:sub(2)
        local colorValue = self[colorName]
        if colorValue then
            return "#" .. colorValue
        else
            return match
        end
    end

    local pattern = "(&%w+)"

    local result = text:gsub(pattern, replaceColor)

    return result
end

local text = "&whiteHello&white World"
print(str:generate_string(text))

你好。我有这样的代码。我想传递一个字符串作为参数,并在函数内部,用十六进制代码替换提到颜色名称的部分,后跟“&”符号。只要最后一个字母后面有空格,此代码就可以正常工作。例如:

"Hello&green World"
结果: “你好#53FF4A世界” 但是,如果模式后面没有空格,例如:
"Hello &greenWorld"
那么代码的行为不正确: 你好&绿色世界 有办法解决这个问题吗? 另外,如果有更有效的方法来实现此代码,我将不胜感激您的意见。

我希望代码能产生这样的结果: 例如:

"Hello &greenWorld"
结果:
"Hello #53FF4AWorld"

arrays string replace lua
2个回答
0
投票

为什么不

["&green"] = "#53FF4A"


0
投票

我同意@darkfrei,你似乎把事情复杂化了。这更简单并且有效:

local MAP = {
    ["&red"] = "#FF0000",
    ["&blue"] = "#4C9FFF",
    ["&purple"] = "#C33AFF",
    ["&green"] = "#53FF4A",
    ["&gray"] = "#E2E2E2",
    ["&black"] = "#000000",
    ["&white"] = "#FFFFFF",
    ["&pink"] = "#FB8DFF",
    ["&orange"] = "#FF8E1C",
    ["&yellow"] = "#FAFF52",
    --TODO Add Colors
}

function colorate(text)
    assert(text and type(text) == "string")

    local result = text
    
    for k,v in pairs(MAP) do
        result = result:gsub(k, v)
    end

    return result
end

local text = "&whiteHello&white World Hello &greenWorld"
print(colorate(text))
-- Output: #FFFFFFHello#FFFFFF World Hello #53FF4AWorld
© www.soinside.com 2019 - 2024. All rights reserved.