Lua: 获取子字符串

例如,我有一个字符串

str = "Beamer-Template!navigation symbols@\\texttt {navigation symbols}"
print(str:gsub('[^!|@%s]+@', ''))

它打印出

Beamer-Template!navigation \texttt {navigation symbols}

但是它应该是

Beamer-Template!\texttt {navigation symbols}

我该如何捕捉空格? 只有 foo@bar 是重要的。该模式对于像

str="foo@bar!baz@foobar!nice|crazy"
-> bar!foobar!nice|crazy

的字符串有效,但是对于有额外空格的字符串

str="foo@bar!baz baz@foobar!nice|crazy"
-> bar!baz foobar!nice|crazy

它不起作用,应为 bar!foobar!nice|crazy

点赞
用户1944004
用户1944004

为了匹配 makeindex 条目,使用 LPEG 语法可能是有用的。 这样,您可以在分隔符处拆分,并根据匹配字段执行语义操作。

local lpeg = assert(require"lpeg")
local C, S = lpeg.C, lpeg.S

local sep = S("@!|")
local str = C((1 - sep)^0)

local idx = str * ( "@" * str / function(match) return "@" .. match end
                  + "!" * str / function(match) return "!" .. match end
                  + "|" * str / function(match) return "|" .. match end)^0

print(idx:match("hello!world@foo|bar"))
$ lua test.lua
hello   !world  @foo    |bar

对评论的回答:将匹配项收集到表中。 根据前缀收集匹配项。

local lpeg = assert(require"lpeg")
local C, Ct, S = lpeg.C, lpeg.Ct, lpeg.S

local sep = S("@!|")
local str = C((1 - sep)^0)

local match = function(expr)
    local prefix = function(prefix)
        return function(match)
            return prefix .. match
        end
    end

    local idx = str * ( "@" * str / prefix("@")
                      + "!" * str / prefix("!")
                      + "|" * str / prefix("|"))^0

    return Ct(idx):match(expr)
end

for _, str in ipairs{
    "hello!world@foo|bar",
    "foo@bar!baz baz@foobar!nice|crazy",
    "foo@bar!baz@foobar!nice|crazy",
    "Beamer-Template!navigation symbols@\\texttt {navigation symbols}"
} do
    local t = match(str)
    print(table.concat(t," "))
end
$ lua test.lua
hello !world @foo |bar
foo @bar !baz baz @foobar !nice |crazy
foo @bar !baz @foobar !nice |crazy
Beamer-Template !navigation symbols @\texttt {navigation symbols}
2018-10-09 09:27:01