Search code examples
javascriptregexgrammarpegjs

How do I match tokens starting with "?" in pegjs


I have to match tokens like this using pegjs:

?xxx ?yyy

I would have thought this would work :

variable 
   = str:?[a-z]+ {  console.log('---->>>',str); return str.join(""); } 

When I parse the source I get and error:

Object ? has no method 'join'

This is because the str variable is not an array of the matched tokens... Any idea how this should be done?


Solution

  • You can either group literals together:

    variable 
        = str:("?"[a-z]+)
    

    in which case str will be ["?",["a","b","c"]] for ?abc, or, if ? is not necessarily the first char, just include it in the class:

    variable 
        = str:[?a-z]+
    

    then you'll get a normal array ["?","a","b","c"].