美文网首页
pegjs学习的小例子

pegjs学习的小例子

作者: 遇酒无缘 | 来源:发表于2018-11-08 19:28 被阅读0次

pegjs官网

1.匹配字符

abc def . ghi . jkl

parser

Express = Terms (_ Dot _ Terms)*
Terms = (Term (_ Term)*)+
Dot = "."
Term = [a-z]+
_ = [ \r\n\t]*
2.匹配START和END之间的字符

number START friend relative office-mate good son ship END long term campus

Text = NotStartString 'START' s:wangString 'END' .+ {return s}
NotStartString = (!'START' .)+ {return text()}
wangString = (!'END' .)+ {return text()}

3.分别计算出$a、$b、$c、$d、$e各自的值

{$a: '1', $b: '$a + 2', $c: '$b + 10', $d: '$a + $b + $c + 10', $e: '$d'}

1).先匹配结构

Expression = "{" Pair ("," _ Pair)* "}" 
Pair = _ key ":" _ value
key = "$" [a-z]+
value = singleQuote ( Formula / Num) singleQuote 
singleQuote = "'"
Formula = key  ( _ "+" _  ( key / Num ) )+
Num = [0-9]+
_ = [ \r\t\n]*

2).再加入计算

{let obj = {} }

Expression = "{" Pair ("," _ Pair)* "}" { return obj}
Pair = _ k:key ":" _ v:value  { obj[k] = v }
key = $("$" [a-z]+)
value = singleQuote x:( Formula / Num) singleQuote {return x}
singleQuote = "'"
Formula = k:key y:(x:( _ "+" _ num:( Num / key:key {return obj[key];}) 
{return num;} )+ 
{ return x.reduce((sum, i) => sum + i, obj[k]);})? 
{return y !== null? y:obj[k];}
Num = [0-9]+ {return parseInt(text(),10)}
_ = [ \r\t\n]*

相关文章

网友评论

      本文标题:pegjs学习的小例子

      本文链接:https://www.haomeiwen.com/subject/ugyvxqtx.html