Lua:使用gmatch条件切割字符串

我正在使用 Lua 编写 Mushclient 插件。Mushclient 包含了 PCRE 模块,可以使用 rex.new 函数编译正则表达式。我不确定是否需要使用它来完成我想做的事情,但我认为可能需要,尽管我宁愿不用。

基本上,我想使用分隔符“,”或“ and ”将一个字符串分割成一个表。但是,这些“分隔符”出现在我想要保留未拆分的项目内的某些情况中(例如 Felix, the Cat)。以下是我已经完成的内容:

false_separators = {"Felix, the Cat", "orange and tan cat", "black and white cat"}
separators = rex.new(" ?(.+?)(?:,| and )")
local sample_text = "a black and white cat, a tabby cat, a giant cat, Felix, the Cat and an orange and tan cat."
index = 1
matches = {}
separators:gmatch(sample_text, function (m, t)
    for k, v in pairs(t) do
          print(v)
          table.insert(matches, v)
    end
 end)

这将输出:

a black
white cat
a tabby cat
a giant cat
Felix
the Cat
an orange

这有两个问题。首先,最后一个项目未包括在内。其次,我还没有想出如何实现我的 false_separators 表。我期望的输出是:

a black and white cat
a tabby cat
a giant cat
Felix, the Cat
an orange and tan cat

我可以通过大量的 gsub 处理来实现它,但这似乎不够优雅,可能有漏洞或运行缓慢:

false_separators = {"Felix, the Cat", "orange and tan cat", "black and white cat"}
local sample_text = "a black and white cat, a tabby cat, a giant cat, Felix, the Cat and an orange and tan cat."

function split_cats(text, false_sep)
    for k, v in ipairs(false_sep) do
        text = text:gsub(v, v:gsub(" ", "_")) -- 将误判为分隔符的匹配项中的空格替换为下划线
    end
    text = text:gsub(" and ", ", "):gsub(", ", ";") -- 替换 " and "(不在下划线周围的)成逗号,然后用分号替换所有不在下划线后面的逗号。分号现在是真正的分隔符。
    m = utils.split (text, ";") or {} -- 用分号拆分
    for i, v in ipairs(m) do
        m[i] = v:gsub("_", " ") -- 删除下划线
    end
    return m
end

table.foreach(split_cats(sample_text, false_separators), print)

输出:

1 a black and white cat
2 a tabby cat
3 a giant cat
4 Felix, the Cat
5 an orange and tan cat.
点赞