wakhaiha
wakhaiha

Reputation: 55

Use single pattern to string match multiple words Lua script

I have simple text as below:

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

I want set all words in the square bracket as the variable in array using Lua. I try this code below:

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

The output is "all 1". My objective is to printout output as

all 1
words 2
are 3
different 4

I have tried to add 3 same patterns as below:

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

It is working. But I don't think it is the best way especially when the text have load of lines like 100, etc. What is the proper way to do it?

thanks in advance.

Upvotes: 2

Views: 8882

Answers (1)

ad absurdum
ad absurdum

Reputation: 21317

Lua patterns do not support repeated captures, but you can use string.gmatch(), which returns an iterator function, with an input string, using the pattern "%[(.-)%]" to capture the desired text:

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

The above code gives output:

all 1
words 2
are 3
different 4

Note that this can be done in a single line, if desired:

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

Also note that there is no need to escape an isolated closing bracket, as this final example demonstrates.

Upvotes: 2

Related Questions