Optional capture of balanced brackets in Lua

Viewed 601

Let's say I have lines of the form:

int[4] height
char c
char[50] userName 
char[50+foo("bar")] userSchool 

As you see, the bracketed expression is optional.

Can I parse these strings using Lua's string.match() ?

The following pattern works for lines that contain brackets:

line = "int[4] height"
print(line:match('^(%w+)(%b[])%s+(%w+)$'))

But is there a pattern that can handle also the optional brackets? The following does not work:

line = "char c"
print(line:match('^(%w+)(%b[]?)%s+(%w+)$'))

Can the pattern be written in another way to solve this?

2 Answers
Related