我正在寻找一种用于分析两种句子的语法,这意味着用空格分隔的单词:
- ID1:单词不以数字开头的句子
- ID2:单词不以数字和数字开头的句子
基本上,语法的结构应该看起来像
ID1 separator ID2  
ID1: Word can contain number like Var1234 but not start with a number  
ID2: Same as above but 1234 is allowed  
separator: e. g. '='
@Bart
我只是尝试添加两个标记'_'并'"'作为 lexer-ruleSpecial供以后在 lexer-rule 中使用Word。即使我没有Special在以下语法中使用,我在 ANTLRWorks 1.4.2 中得到以下错误:
The following token definition can never be match because prior tokens match the same input: Special
 
But when I add fragmentbefore Special,我没有得到那个错误。为什么?  
grammar Sentence1b1;
tokens
{
  TCUnderscore  = '_' ;
  TCQuote       = '"' ;
}
assignment
  :  id1 '=' id2
  ;
id1
  :  Word+
  ;
id2
  :  ( Word | Int )+
  ;
Int
  :  Digit+
  ;
// A word must start with a letter
Word
  :  ( 'a'..'z' | 'A'..'Z') ('a'..'z' | 'A'..'Z' | Digit )*
  ;
Special
  : ( TCUnderscore | TCQuote )
  ;
Space
  :  ( ' ' | '\t' | '\r' | '\n' ) { $channel = HIDDEN; }
  ;
fragment Digit
  :  '0'..'9'
  ;
Special然后应在 lexer-rule 中使用 Lexer- rule Word:
Word
  :  ( 'a'..'z' | 'A'..'Z' | Special ) ('a'..'z' | 'A'..'Z' | Special | Digit )*
  ;
