首页 > 解决方案 > 用于单行注释的 JavaCC 正则表达式

问题描述

我正在为自定义语言编写词法分析器,并希望匹配以 # 开头的单行注释,就像在 python 中一样,但这里的注释总是从行首开始。例子:

#this is a comment and #this is not a comment

我试过这个:"^#" (~["\n"])* ("\n")? 但不工作。我怎样才能做到这一点?

标签: javacc

解决方案


不幸的是,JavaCC 不支持^for start of line,也不支持$for end of line。

您可以使用词法状态。使用默认状态*作为行的开头。例如:

// If at the start of a line, skip a # and all other charaters on the line.
// Stay in the same state.
<*>          SKIP : { <COMMENT : "#" (~["\n"])* ("\n") > : * }

// Skip any newlines and return to (or stay in) the start of line state.
<*, MIDLINE> SKIP : { <NEWLINE : "\n" >                  : * }

// Skip any other white space.
<*, MIDLINE> SKIP : { <WHITESPACE : " " | "\t"  >        : MIDLINE }

// If not at the start of line, a # is a token.
<MIDLINE>    TOKEN : { <HASH    : "#" >                   : MIDLINE }

// Numbers can be at the start of a line or the middle of a line.
// After a number, we are no longer at the start of line.
<*, MIDLINE> TOKEN : { <NUMBER : ["0"-"9"]+ >            : MIDLINE }

等等。


推荐阅读