我只是使用ANTLR4来编写一些语法。在我编写java代码输入数据后,ANTLR为我生成解析树。但是,在检查语法后,我只需要终端,我找不到任何方法只返回每个终端给我。语法如下:
grammar Expr;
prog: stat;
stat: (createSQL | insertSQL) ';' stat*
|(createSQL | insertSQL) ';'?;
createSQL: CREATE TABLE NAME '(' att_def ')'
;
insertSQL: INSERT INTO NAME ('(' (att_names) ')')? VALUES '(' att_values ')'
;
att_names: NAME ',' att_names
| NAME
;
att_values : (NUM | str) (',' (NUM | str))*
;
str : '\'' .*? '\''
;
att_def : NAME ATTTYPE PRIMARYKEY
| NAME ATTTYPE PRIMARYKEY ',' subatt_def
| NAME ATTTYPE ',' att_def
| NAME ATTTYPE
;
subatt_def: NAME ATTTYPE ',' subatt_def
| NAME ATTTYPE
;
PRIMARYKEY: [Pp] [Rr] [Ii] [Mm] [Aa] [Rr] [Yy] ' ' [Kk] [Ee] [Yy]
;
ATTTYPE : 'varchar' '(' [1-3]INT ')'
| 'varchar' '(' [1-9] ')'
| 'varchar' '(' '40' ')'
| 'int'
;
INSERT: [iI] [nN] [sS] [eE] [rR] [tT];
INTO : [iI] [nN] [tT] [oO];
VALUES : [vV] [aA] [lL] [uU] [eE] [sS];
NUM : [0-9]+;
INT : [0-9];
CREATE: [cC] [rR] [eE] [aA] [tT] [eE];
TABLE: [tT] [aA] [bB] [lL] [eE];
NAME: [a-zA-Z]([a-z-A-z] | '_' | '-')*;
NEWLINE: ['\r'? '\n']->skip;
TAB : [\t];
输入:
创建TABLE Person(person_id varchar(25)PRIMARY KEY,year int,age int);
插入Person(person_id,year,age)值('我是super man_lin',1988,25);
java代码:
public class ANTLRDemo{
public static void main(String[] args) throws Exception{
String inputFile = "t.expr";
InputStream is = new FileInputStream(inputFile);
ANTLRInputStream input = new ANTLRInputStream(is);
ExprLexer lexer = new ExprLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExprParser parser = new ExprParser(tokens);
ParseTree tree = parser.prog();
System.out.println(tree.toStringTree(parser));}}
有人可以帮助我吗?我只想得到一个包含所有终端的字符串数组,除了'(',')',','。
答案 0 :(得分:0)
分析树:
/** Return the combined text of all leaf nodes. Does not get any
* off-channel tokens (if any) so won't return whitespace and
* comments if they are sent to parser on hidden channel.
*/
String getText();
泰尔