3

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.

Jess Bowers
  • 2,846
  • 1
  • 22
  • 42
rkmax
  • 17,633
  • 23
  • 91
  • 176
  • I'm not familiar with peg but regex it is like this `^variable(?:\.variable)+$` just replace variable with escaped string. – Vitim.us Nov 05 '13 at 14:20

1 Answers1

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.

rkmax
  • 17,633
  • 23
  • 91
  • 176
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • works with `return "." + s;` on the first return and change the `*` by `+` for avoid the first rule write on the question – rkmax Nov 05 '13 at 14:28
  • @rkmax uhh ... I don't understand what that comment means. I used `*` in the second part of the rule so that "foo" would parse. Do you *want* the "." characters? If so then yes I see. – Pointy Nov 05 '13 at 14:33
  • sorry @Pointy I sure do not specify, you must comply with the list of the beginning of the question – rkmax Nov 05 '13 at 14:35
  • @rkmax ah OK yes I see that now. Sorry I missed it. – Pointy Nov 05 '13 at 14:36
  • @rkmax if you change it to `+` then "foo" by itself will not parse - oh wait it's not supposed to. OK I should have read the specification more carefully! – Pointy Nov 05 '13 at 14:48