Antlr4 使用转义字符分析带引号的字符串

Antlr4 使用转义字符分析带引号的字符串,antlr4,Antlr4,我在分析antlr4中的格式行列表时遇到问题 * this is a string * "first" this is "quoted" * this is "quoted with \" " 我想构建一个解析树,就像 (list (line * (value (string this is a string))) (line * (value (parameter first) (string this is) (parameter quoted))) (line * (val

我在分析antlr4中的格式行列表时遇到问题

* this is a string
*  "first"  this is "quoted"
* this is "quoted with \" "
我想构建一个解析树,就像

(list 
(line * (value (string this is a string))) 
(line * (value (parameter first) (string   this is) (parameter quoted))) 
(line * (value (string this is) (parameter quoted with " )))
)
我有一个这种格式的antlr4语法

grammar List;
list : line+;
line : '*' (WS)+ value* NEWLINE;
value : string
      | parameter
      ;
string : ((WORD) (WS)*)+;
parameter : '"'((WORD) (WS)*)+ '"';
WORD : (~'\n')+;
WS : '\t' | ' ';
NEWLINE     : '\n';
但这在“*”本身的第一个字符识别中失败了,这让我感到困惑


第1行:0不匹配的输入“*这是一个字符串“期望”*”

问题是您的lexer太贪婪了。规则

WORD : (~'\n')+;
几乎所有东西都匹配。这会导致lexer为您的输入生成以下标记:

  • 令牌1:
    WORD
    *这是一个字符串
  • 令牌2:
    NEWLINE
  • 令牌3:
    WORD
    (`*“first”这是“quoted”)
  • 令牌4:
    NEWLINE
  • 令牌5:
    WORD
    *这是“引用\
是的,这是正确的:只有
WORD
NEWLINE
标记。ANTLR的lexer试图用尽可能多的字符构造标记,它不会“监听”解析器试图匹配的内容

错误消息:

第1行:0不匹配的输入“*这是一个字符串”,应为“*”

正在告诉您:在第1行的索引0中,遇到了带有文本
“*这是一个字符串”
(键入
WORD
)的标记,但解析器正在尝试匹配该标记:
“*”

请尝试以下方法:

grammar List;

parse
 : NEWLINE* list* NEWLINE* EOF
 ;

list
 : item (NEWLINE item)*
 ;

item
 : '*' (STRING | WORD)* 
 ;

BULLET : '*';
STRING : '"' (~[\\"] | '\\' [\\"])* '"';
WORD : ~[ \t\r\n"*]+;
NEWLINE : '\r'? '\n' | '\r';
SPACE : [ \t]+ -> skip;
它将解析示例输入,如下所示:

(parse 
  (list 
    (item 
      * this is a string) \n 
    (item 
      * "first" this is "quoted") \n 
    (item 
      * this is "quoted with \" ")) 
   \n 
  <EOF>)
(解析)
(名单
(项目
*这是一个字符串)\n
(项目
*“首先”这是“引用”)\n
(项目
*这是“引用\”))
\n
)