首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用pegjs语法只解析注释?

如何使用pegjs语法只解析注释?
EN

Stack Overflow用户
提问于 2016-07-22 23:02:50
回答 1查看 189关注 0票数 3

我写了一个pegjs语法,它可以解析任何js/c风格的注释。然而,这并不是很有效,因为我只设法捕获了注释本身,而忽略了其他所有内容。我应该如何改变这个语法,使其只解析任何类型的输入中的注释?

语法:

代码语言:javascript
复制
Start
  = Comment

Character
  = .

Comment
  = MultiLineComment
  / SingleLineComment

LineTerminator
  = [\n\r\u2028\u2029]

MultiLineComment
  = "/*" (!"*/" Character)* "*/"

MultiLineCommentNoLineTerminator
  = "/*" (!("*/" / LineTerminator) Character)* "*/"

SingleLineComment
  = "//" (!LineTerminator Character)*

输入:

代码语言:javascript
复制
/**
 * Trending Content
 * Returns visible videos that have the largest view percentage increase over
 * the time period.
 */

Other text here

错误

代码语言:javascript
复制
Line 5, column 4: Expected end of input but "\n" found.
EN

回答 1

Stack Overflow用户

发布于 2017-01-27 08:59:27

在考虑注释(单行或多行)之前,您需要重构以专门捕获行内容,如下所示:

代码语言:javascript
复制
lines = result:line* {
  return result
}

line = WS* line:$( !'//' CHAR )* single_comment ( EOL / EOF ) { // single-comment line
  return line.replace(/^\s+|\s+$/g,'')
}
/ WS* line:$( !'/*' CHAR )* multi_comment ( EOL / EOF ) { // mult-comment line
  return line.replace(/^\s+|\s+$/g,'')
}
/ WS* line:$CHAR+ ( EOL / EOF ) { // non-blank line
  return line.replace(/^\s+|\s+$/g,'')
}
/ WS* EOL { // blank line
  return ''
}

single_comment = WS* '//' CHAR* WS*

multi_comment = WS* '/*' ( !'*/' ( CHAR / EOL ) )* '*/' WS*

CHAR = [^\n]
WS = [ \t]
EOF = !.
EOL = '\n'

它在运行时:

代码语言:javascript
复制
no comment here

single line comment // single-comment HERE

test of multi line comment /*

  multi-comment HERE

*/

last line

返回:

代码语言:javascript
复制
[
  "no comment here",
  "",
  "single line comment",
  "",
  "test of multi line comment",
  "",
  "last line"
]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38529702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档