Make a Grammar expression for STRING.STRING.STRING on PEG.js

孤街浪徒 提交于 2020-01-24 11:44:53

问题


I am looking for a peg.js grammar expression for matching against:

  • "variable" # Fails
  • "variable." # Fails
  • "" # Fails
  • "variable.variable" # Ok
  • "variable.variable.variable.variable.variable" #Ok

input I expect

  • {PATH: "variable.variable"}
  • {PATH: "variable.variable.variable.variable.variable"}

Sample.pegjs

start = 
    PATH_EXP

STRING_EXP =
    chars:[0-9a-zA-Z_]+ { return chars.join(""); }

PATH_EXP =    
    path:(STRING_EXP "." STRING_EXP) { return {PATH: path.join("")}; }

I don't know how to make the expression repeat, but also make it optional.


回答1:


Here's what I came up with to get rid of the "." characters. I'll admit that I've never used peg.js before :)

PATH_EXP =    
    (first:STRING_EXP rest:("." STRING_EXP)*) {
      return {
        PATH: first +  
              rest.map(function(v) {
                return v[1]; 
              }).join("")
      };
    }

edit — oh wait this is better:

PATH_EXP = 
    first:STRING_EXP rest:("." s:STRING_EXP { return "." + s; })+ {
      return {
        PATH: first + rest.join('')
      };
    }

edit — clearly if you want the "." characters you'd include them in the action inside that second part. Missed that part of the question.



来源:https://stackoverflow.com/questions/19790748/make-a-grammar-expression-for-string-string-string-on-peg-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!