Search code examples
peg

How to define a rule to match with a pattern multiple times in PEG.js?


I'm trying to parse a file where the pattern might be seen multiple times:

G04 hello world*
G04 foo bar*

The corresponding PEG.js grammar is:

Comment
  = "G04" _ content:String* _ EOL
  {
    return content
  }

_ "whitespace"
  = [ \t\n\r]*

String
  = value:[a-zA-Z0-9.(): _-]+
  {
    return value.join('') 
  }

EOL
  = [*] _ 

However, I'm getting the following error:

Line 2, column 1: Expected end of input but "G" found.

How do I make this Comment rule to match multiple times?


Solution

  • You should just be able to add a new start rule that matches multiple Comments:

    Comments
      = Comment+
    
    Comment
      = "G04" _ content:String* _ EOL
      {
        return content
      }
    
    _ "whitespace"
      = [ \t\n\r]*
    
    String
      = value:[a-zA-Z0-9.(): _-]+
      {
        return value.join('') 
      }
    
    EOL
      = [*] _
    

    Output:

    [
       [
          "hello world"
       ],
       [
          "foo bar"
       ]
    ]