local lpeg = require "lpeg"
match=lpeg.match
local C, P, R, S, V = lpeg.C, lpeg.P, lpeg.R, lpeg.S, lpeg.V
local Carg, Cc, Cp, Ct, Cs, Cg, Cf = lpeg.Carg, lpeg.Cc, lpeg.Cp, lpeg.Ct, lpeg.Cs, lpeg.Cg, lpeg.Cf
local guillemet=P('"')
local Separateur=S(',;')
local caractere=C(R'09'+R'az')^1-guillemet
-- Lexical Elements
local Space = S(" \n\t")^0
--local Number = C(S"+-"^-1 * R("09")^1) * Space
local Number = C(R("09")^1) * Space
local TermOp = C(S("+-")) * Space
local FactorOp = C(S("*/")) * Space
local Open = "(" * Space
local Close = ")" * Space
function parenthese(_expression_)
return 'par{' .. _expression_ .. '}'
end
-- Grammar
local Exp, Term, Factor, Formule = V"Exp", V"Term", V"Factor", V"Formule"
local Grammaire = P { V'Exp',
Exp = Term * Cg(TermOp * Term)^0,
Term = Formule * Cg(FactorOp * Formule)^0+Cc('(')*TermOp*Formule*Cc(')')*Cg(FactorOp * Formule)^0,
-- the following line works as expected : 1 + par{ 5 + 4 }
Parentheses=Open*Cc('par{')*Exp*Cc('}')*Close,
-- the following line doesn't work as expected : 1 + par{5}
-- Parentheses=Open*Cf(Exp,parenthese)*Close,
texte = Cc('text{')*guillemet*C((1-guillemet)^0)*guillemet*Cc('}'),
sans_texte=(Number^1+caractere^1),
Formule=V'texte'+V'sans_texte'+V'Parentheses'
}
print(match(Grammaire,'1+(5+4)'))