使用gmatch将模式拆分为多个表

问题描述 投票:1回答:1

我试图使用模式将我的文本gsplit到多个表中。

所以这是我的意见。

\x10Hello\x0AWorld

这是我在我的输出中所期望的,\x0A

{{'\x10', 'Hello'}, {'\x0A', 'World'}}

这是我到目前为止所尝试的。

local function splitIntoTable(input)
    local output = {}
    for code, text in (input):gmatch('(\\x%x+)(.*)') do
        print(code .. ' ' .. text);
        table.insert(output, { code, text })
    end
    return output
end

我在gmatch制作了2个正则表达式组,第一组用于十六进制,第二组用于文本,我不知道为什么这不起作用。 print语句永远不会被执行,因此循环永远不会被使用。

lua string-matching
1个回答
0
投票

模式'\\x%x+'匹配文字反斜杠,x和十六进制数字序列。它与由十六进制转义符(如'\x0A')生成的ASCII字符不匹配。

您需要将其替换为方括号中的字符类,例如'[\x10\x0A]'。您必须使用您在匹配中的该位置期望的任何ASCII字符(或其他字节)填写字符类。

不幸的是,这种模式只会在像'\x10Hello\x0AWorld'这样的字符串中匹配一次。模式的第二部分也需要修改。

local function splitIntoTable(input)
    local output = {}
    for code, text in (input):gmatch('([\x10\x0A])(.*)') do
        print(code .. ' ' .. text);
        table.insert(output, { code, text })
    end
    return output
end
© www.soinside.com 2019 - 2024. All rights reserved.