我想用我的语法忽略 whitespaces 和 new lines ,因此PEG.js输出中缺少它们。此外,括号内的文字应以新数组的形式返回。
语法
start
= 'a'? sep+ ('cat'/'dog') sep* '(' sep* stmt_list sep* ')'
stmt_list
= exp: [a-zA-Z]+ { return new Array(exp.join('')) }
sep
= [' '\t\r\n]
测试用例
a dog( Harry )
输出
[
"a",
[
" "
],
"dog",
[],
"(",
[
" "
],
[
"Harry"
],
[
" "
],
")"
]
我想要的输出
[
"a",
"dog",
[
"Harry"
]
]
答案 0 :(得分:27)
你必须更多地分解语法,使用更多的“非终端”(不确定这是否是你在PEG中所称的那些):
start
= article animal stmt_list
article
= article:'a'? __ { return article; }
animal
= animal:('cat'/'dog') _ { return animal; }
stmt_list
= '(' _ exp:[a-zA-Z]+ _ ')' { return [ exp.join('') ]; }
// optional whitespace
_ = [ \t\r\n]*
// mandatory whitespace
__ = [ \t\r\n]+
感谢您提出这个问题!
修改强>
要提高可读性,请制作两个作品:_
和__