所以我遇到的问题是将一个字符串与括号或任何其他符号分开,我想制作一个函数,你可以把2个符号作为“边框符号”来包含我想要捕获的字符串部分和然后我会让函数查找所述符号并分离出字符串。如果这是可能的话,我在徘徊,如果是这样,我将如何去做这件事。
您可以使用'plain'字符串查找功能,这样您就不必担心转义魔术字符。
https://www.lua.org/manual/5.3/manual.html#pdf-string.find
-- input: str, string to seperate
-- b1, border symbol 1
-- b2, border symbol 2
-- incl, true to include the border symbols in the returned value
-- return: sub, the substring between the border symbols
-- or nil if the border symbols don't appear in str
local function border(str, b1, b2, incl)
local sub
local i = str:find(b1, 1, true) -- using 'plain' means no escaping of magic
if i == nil then return nil end -- characters
local j = str:find(b2, i+1, true)
if j == nil then return nil end
if incl then
sub = str:sub(i, j)
else
sub = str:sub(i+1,j-1)
end
return sub
end
local test1 = "hello(world)"
local test2 = "(hello] world"
local test3 = "(hello-)(+world)"
local test4 = "hello, world"
print()
print(border(test1, '(', ')', true))
print(border(test1, '(', ')', false),"\n")
print(border(test2, '(', ']', true))
print(border(test2, '(', ']', false),"\n")
print(border(test3, '-', '+', true))
print(border(test3, '-', '+', false),"\n")
print(border(test4, ',', ',', true))
print(border(test4, ',', ',', false),"\n")
将输出:
> lua border.lua
(world)
world
(hello]
hello
-)(+
)(
nil
nil