Search code examples
javascriptparsingcompiler-constructionpeg

PEG.js Allow any text between two tags


I am having trouble defining an expression that allows any text between two tags (including those tags).

Examples:

#ifdef
 asdasdasdasdasdsasd
asdasdasdasdasdasdasd
asdasdasdasdasdasasd
#endif

It should also allow

#ifdef
asdasdasd
asdasdsad
#ifdefasdasdasd
asdasdasd
#endif#endif
asdasdasd
asdasdasd
#endif

So as you can see, as long as it starts and ends with #ifdef and endif any text inside should be okay.

Can anyone help me create such an expression?

What I tried so far is this:

H_IF_IGNORE 
= ("#ifdef) _
  H_IF_IGNORE / (!"#endif"i SourceCharacter)*
  "#endif"

But it is not working very well, and ends up consuming more text after the last endif.

Best regards


Solution

  • The inner part can either be another #ifdef or a SourceCharacter repeated, so both parts need to be in parenthesis.

    Try something along these lines:

    H_IF_IGNORE
    = "#ifdef" _*
      (H_IF_IGNORE / (!"#endif" SourceCharacter))* _*
      "#endif"
    
    SourceCharacter = .
    
    _ = [\s\n]