你的语法:
grammar Test;
sentence_with_int
: sentence {System.out.println("Parsed: sentence='"+$sentence.text+"'");}
INT {System.out.println("Parsed: int='"+$INT.text+"'");}
;
sentence
: (ANY_WORD | INT)+
;
ANY_WORD
: ('a'..'z' | 'A'..'Z')+
;
INT
: ('0'..'9')+
;
WS
: (' ' | '\t' | '\r' | '\n') {$channel=HIDDEN;}
;
就是这样。下面是一个小测试工具:
import org.antlr.runtime.*;
public class Demo {
public static void main(String[] args) throws Exception {
ANTLRStringStream in = new ANTLRStringStream("the number of size 14 shoes bought was 3");
TestLexer lexer = new TestLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
TestParser parser = new TestParser(tokens);
parser.sentence_with_int();
}
}
首先生成一个解析器&lexer(假设所有文件和antlr jar都在同一目录中):
java -cp antlr-3.2.jar org.antlr.Tool Test.g
编译所有
.java
源文件:
javac -cp antlr-3.2.jar *.java
最后运行
Demo
班级:
java -cp .:antlr-3.2.jar Demo
(
在Windows上,替换
:
用一个
;
)
产生以下输出:
Parsed: sentence='the number of size 14 shoes bought was'
Parsed: int='3'