我有如下简单文本:
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"。我的目标是打印输出为
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模式不支持重复捕获,但您可以使用string.gmatch()
,它返回一个迭代器函数,并带有一个输入字符串,使用模式"%[(.-)%]"
来捕获所需的文本:
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
还需要注意的是,正如最后一个例子所展示的那样,不需要转义一个孤立的右括号。