Search code examples
javascriptregexgrammarxregexp

Regex for a recursive grammar in javascript


Suppose I have the following fictional grammar, with a recursive definition for clause.

sentence := clause +
subject := (qualifier *) subjectiveNoun
objects := object +
object := nothing | (qualifier *) objectiveNoun
clause := subject objects verb
qualifier := adjective | clause

Assuming everything else has a non recursive definition, how should can approach writing a javascript grammar for 'clause'? If someone is familiar with the XRegExp library to do this, that would be an added plus.


Solution

  • The XRegExp library does support recursive matching1, but what is your goal here? If you're able to match this with regex, then what? If you're planning to process the parse tree, then regex is of little use, this will only tell you the source matched or not. In that case, have a look into PEG.js or Jison.

    1 http://xregexp.com/plugins/#matchRecursive