ANTLR:Unicode字符扫描

问题:无法正确打印Unicode字符。

这是我的语法:

options { k=1; filter=true; // Allow any char but \uFFFF (16 bit -1) charVocabulary='\u0000'..'\uFFFE'; } ANYCHAR :'$' | '_' { System.out.println("Found underscore: "+getText()); } | 'a'..'z' { System.out.println("Found alpha: "+getText()); } | '\u0080'..'\ufffe' { System.out.println("Found unicode: "+getText()); } ; 

调用词法分析器的main方法的代码片段:

 public static void main(String[] args) { SimpleLexer simpleLexer = new SimpleLexer(System.in); while(true) { try { Token t = simpleLexer.nextToken(); System.out.println("Token : "+t); } catch(Exception e) {} } } 

对于输入“ठ” ,我得到以下输出:

 Found unicode: Token : ["à",,line=1,col=7] Found unicode: Token : ["¤",,line=1,col=8] Found unicode: Token : [" ",,line=1,col=9] 

似乎词法分析器将Unicode char“ठ”视为三个独立的字符。 我的目标是扫描并打印“ठ”。

您的问题不在ANTLR生成的词法分析器中,而是在Java流中传递给它。 流只读取字节(不会在编码中解释它们),您看到的是UTF-8序列。

如果是ANTLR 3,则可以使用ANTLRInputStream构造函数将ancoding作为参数:

 ANTLRInputStream (InputStream input, String encoding) throws IOException