2

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.

3
  • Are these lines in a file, or is it a single string that you want to search? Commented Feb 14, 2017 at 8:59
  • thank you for prompt reply. it is a single string that contains all the words above. Commented Feb 14, 2017 at 9:16
  • array = {} for s in s:gmatch '%b[]' do array[#array+1] = s:sub(2,-2) end Commented Feb 14, 2017 at 21:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.