PegJS - match all characters including ) except if ) is the last character

802 Views Asked by At

I am writing a PegJS grammar to parse SQL statements. I'm working on splitting a function into function_id(function_args). For function args I want to match all characters including ( and ) except the last ), this being necessary for nested functions.

How do I write a rule to match all characters which includes ) except when ) is the last character in the string.

The grammar is given below

 Function 
 = func_name open_p args close_p

func_name 
= name:[A-Z]+ {return name.join('');}

open_p
= "("

close_p
= ")"

args
= ar:(.*[^)]) {return ar.join('');}

and the test string is

AVG(A + AVG(B + C))
1

There are 1 best solutions below

0
On BEST ANSWER

Rules to handle the arguments correctly can help. Also, instead of using {return name.join('');} you can use $() notation in the rule to combine parsed strings.

args can either be function or nonfunction repeated. nonfunction captures everything that is not a function by look ahead.

function 
 = func_name open_p (args+ / "") close_p

func_name 
= $([A-Z]+)

open_p
= "("

close_p
= ")"

args
= function / nonfunction

nonfunction
= $((!(function / close_p) .)+)