Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional capture of balanced brackets in Lua

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?

like image 506
Niccolo M. Avatar asked Mar 21 '23 06:03

Niccolo M.


1 Answers

Unlike regular expressions, ? in Lua pattern matches a single character.

You can use the or operator to do the job like this:

line:match('^(%w+)(%b[])%s+(%w+)$') or line:match('^(%w+)%s+(%w+)$')

A little problem with it is that Lua only keeps the first result in an expression. It depends on your needs, use an if statement or you can give the entire string the first capture like this

print(line:match('^((%w+)(%b[])%s+(%w+))$') or line:match('^((%w+)%s+(%w+))$'))
like image 146
Yu Hao Avatar answered Mar 23 '23 20:03

Yu Hao