Extra grip on 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 can see, the expression in parentheses is optional.

Can I parse these lines using Lua string.match()?

The following figure works for strings containing brackets:

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

But is there a pattern that can handle additional brackets as well? The following is not work :

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

Is it possible to write a template in another way to solve this problem?

+4
source share
2 answers

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

or :

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

, Lua . , if ,

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

LPeg , .

local re = require're'

local p = re.compile( [[
    prog <- stmt* -> set
    stmt <- S { type } S { name }
    type <- name bexp ?
    bexp <- '[' ([^][] / bexp)* ']'
    name <- %w+
    S    <- %s*
]], {set = function(...)
    local t, args = {}, {...}
    for i=1, #args, 2 do t[args[i+1]] = args[i] end
    return t
end})

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

for k, v in pairs(p:match(s)) do print(k .. ' = ' .. v) end

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

All Articles