最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ignore whitespace with PEG.js - Stack Overflow

programmeradmin1浏览0评论

I want to ignore whitespaces and new lines with my grammar so they are missing in the PEG.js output. Also, a literal within brackets should be returned in a new array.

Grammar

start
  = 'a'? sep+ ('cat'/'dog') sep* '(' sep* stmt_list sep* ')'

stmt_list
  = exp: [a-zA-Z]+ { return new Array(exp.join('')) }

sep
  = [' '\t\r\n]

Test case

a dog( Harry )

Output

[
   "a",
   [
      " "
   ],
   "dog",
   [],
   "(",
   [
      " "
   ],
   [
       "Harry"
   ],
   [
      " "
   ],
   ")"
]

Output I want

[
   "a",
   "dog",
   [
      "Harry"
   ]
]

I want to ignore whitespaces and new lines with my grammar so they are missing in the PEG.js output. Also, a literal within brackets should be returned in a new array.

Grammar

start
  = 'a'? sep+ ('cat'/'dog') sep* '(' sep* stmt_list sep* ')'

stmt_list
  = exp: [a-zA-Z]+ { return new Array(exp.join('')) }

sep
  = [' '\t\r\n]

Test case

a dog( Harry )

Output

[
   "a",
   [
      " "
   ],
   "dog",
   [],
   "(",
   [
      " "
   ],
   [
       "Harry"
   ],
   [
      " "
   ],
   ")"
]

Output I want

[
   "a",
   "dog",
   [
      "Harry"
   ]
]
Share Improve this question asked Nov 24, 2011 at 12:37 MatthiasMatthias 7,5216 gold badges57 silver badges90 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 29

You have to break up the grammar more, using more "non-terminals" (not sure if that's what you call them in a PEG):

start
  = article? animal stmt_list

article
  = article:'a' __ { return article; }

animal
  = animal:('cat'/'dog') _ { return animal; }

stmt_list
  = '(' _ exp:[a-zA-Z]+ _ ')' { return [ exp.join('') ]; }

// optional whitespace
_  = [ \t\r\n]*

// mandatory whitespace
__ = [ \t\r\n]+

Thanks for asking this question!

Edit: To increase readability, have two productions: _ and __

发布评论

评论列表(0)

  1. 暂无评论