如何在PEG.js中定义一个规则来多次匹配一个模式?

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

我正在尝试解析一个文件,其中的模式可能会被多次看到:

G04 hello world*
G04 foo bar*

对应的PEG.js语法为:

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

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

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

EOL
  = [*] _ 

但是,我收到以下错误:

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

如何使此 Comment 规则匹配多次?

您应该能够添加匹配多个 Comment 的新开始规则:

Comments
  = Comment+

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

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

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

EOL
  = [*] _

输出:

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