You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lua中将带颜色标记的字符串提取为对象数组?

Lua 带颜色标记的字符串解析实现

问题描述

需要将包含花括号包裹十六进制颜色标记(如{FF5050})的字符串转换为对象数组,每个对象包含对应文本片段及其前置指定的颜色值。尝试使用gmatch时无法获取分隔符,且ts-to-lua转译器不兼容JS风格正则。示例需求如下:

local text = "Welcome to thing xyz, {FF5050}username{FFFFFF}!";
local processedText = magicalTextProcessor(text);
--[[
  预期返回:
  [
     { text: "Welcome to thing xyz, ", color: "FFFFFF" },
     { text: "username", color: "FF5050" },
     { text: "!", color: "FFFFFF" },
  ] 
]]

实现方案

利用Lua原生的字符串匹配能力,通过构造合适的正则模式捕获文本片段和颜色值,即可实现需求。以下是完整的magicalTextProcessor函数实现:

function magicalTextProcessor(text)
    local result = {}
    local currentColor = "FFFFFF" -- 默认初始颜色
    local lastPos = 1

    -- 匹配颜色标记及前置文本,捕获两个分组:前置文本、颜色值
    for preText, color in string.gmatch(text, "(.-){(%x%x%x%x%x%x)}") do
        -- 若前置文本非空,添加到结果数组
        if preText ~= "" then
            table.insert(result, {text = preText, color = currentColor})
        end
        -- 更新当前颜色为刚捕获的颜色值
        currentColor = color
        -- 更新指针位置,避免重复匹配
        lastPos = lastPos + #preText + #color + 2
    end

    -- 处理字符串末尾未被匹配的剩余文本
    local remainingText = string.sub(text, lastPos)
    if remainingText ~= "" then
        table.insert(result, {text = remainingText, color = currentColor})
    end

    return result
end

-- 测试示例
local text = "Welcome to thing xyz, {FF5050}username{FFFFFF}!";
local processedText = magicalTextProcessor(text);

-- 打印结果验证
for _, item in ipairs(processedText) do
    print(string.format("text: '%s', color: '%s'", item.text, item.color))
end

关键细节说明

  • 匹配模式:(.-){(%x%x%x%x%x%x)}
    • (.-):非贪婪匹配,确保只捕获当前颜色标记前的文本,不会覆盖后续的标记内容
    • {(%x%x%x%x%x%x)}:精准匹配6位十六进制颜色值,自动去除花括号捕获纯颜色字符串
  • 初始颜色:默认设为FFFFFF,与示例中的默认文本颜色保持一致
  • 剩余文本处理:循环结束后检查字符串末尾未被匹配的部分,避免遗漏内容

内容的提问来源于stack exchange,提问作者szkiddaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:45:33