3

我正在寻找一个 peg.js 语法表达式来匹配:

  • "variable"# 失败
  • "variable."# 失败
  • ""# 失败
  • "variable.variable"# 好的
  • "variable.variable.variable.variable.variable"#好的

我期望的输入

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

示例.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("")}; }

我不知道如何使表达式重复,但也使它成为可选的。

4

1 回答 1

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.

于 2013-11-05T14:09:48.390 回答