.+?
在词法分析器规则的末尾将始终匹配单个字符。但是.+
会尽可能多地消耗,这在 ANTLR v3(可能也是 v4)的规则末尾是非法的。
您可以做的只是匹配一个字符,然后在解析器中将它们“粘合”在一起:
unknowns : Unknown+ ;
...
Unknown : . ;
编辑
...但我只有一个词法分析器,没有解析器...
啊,我明白了。然后你可以覆盖该nextToken()
方法:
lexer grammar Lex;
@members {
public static void main(String[] args) {
Lex lex = new Lex(new ANTLRInputStream("foo, bar...\n"));
for(Token t : lex.getAllTokens()) {
System.out.printf("%-15s '%s'\n", tokenNames[t.getType()], t.getText());
}
}
private java.util.Queue<Token> queue = new java.util.LinkedList<Token>();
@Override
public Token nextToken() {
if(!queue.isEmpty()) {
return queue.poll();
}
Token next = super.nextToken();
if(next.getType() != Unknown) {
return next;
}
StringBuilder builder = new StringBuilder();
while(next.getType() == Unknown) {
builder.append(next.getText());
next = super.nextToken();
}
// The `next` will _not_ be an Unknown-token, store it in
// the queue to return the next time!
queue.offer(next);
return new CommonToken(Unknown, builder.toString());
}
}
Whitespace : [ \t\n\r]+ -> skip ;
Punctuation : [.,:;?!] ;
Unknown : . ;
运行它:
java -cp antlr-4.0-complete.jar org.antlr.v4.Tool Lex.g4
javac -cp antlr-4.0-complete.jar *.java
java -cp .:antlr-4.0-complete.jar Lex
将打印:
未知的“富”
标点符号','
未知的“酒吧”
标点符号“。”
标点符号“。”
标点符号“。”