使用单一模式字符串匹配多个单词 Lua 脚本

Use single pattern to string match multiple words Lua script

我有如下简单的文字:

Hello World [all 1]
Hi World [words 2]
World World [are 3]
Hello Hello [different 4]

我想使用Lua将方括号中的所有单词设置为数组中的变量。 我尝试下面的代码:

text = 'Hello World [all 1]\nHi World [words 2]\nWorld World [are 3]\nHello Hello [different 4]'

array = {string.match(text, '[%a%s]*%[([%a%s%d]*)%]')}

for i = 1,#array do
print(array[i])
end

输出为"all 1"。我的 objective 是打印输出为

all 1
words 2
are 3
different 4

我已尝试添加 3 个相同的模式,如下所示:

array = {string.match(text, '[%a%s]*%[([%a%s%d]*)%].-[%a%s]*%[([%a%s%d]*)%].-[%a%s]*%[([%a%s%d]*)%].-[%a%s]*%[([%a%s%d]*)%]')}

正在运行。但我不认为这是最好的方法,尤其是当文本有很多行,如 100 等时。正确的方法是什么?

提前致谢。

Lua 模式 do not support repeated captures,但您可以使用 string.gmatch(),其中 returns 一个迭代器函数,带有输入字符串,使用模式 "%[(.-)%]"捕获所需的文本:

text = 'Hello World [all 1]\nHi World [words 2]\nWorld World [are 3]\nHello Hello [different 4]'

local array = {}
for capture in string.gmatch(text, "%[(.-)%]") do
   table.insert(array, capture)
end

for i = 1, #array do
   print(array[i])
end

以上代码给出输出:

all 1
words 2
are 3
different 4

请注意,如果需要,这可以在一行中完成:

array = {} for c in string.gmatch(text, "%[(.-)]") do table.insert(array, c) end

另请注意,如最后一个示例所示,无需转义单独的右括号。