[英]How to Get ID Lexer from code that has tokenize in ANTLR
我有一個詞法分析器類,它確定令牌ID詞法分析器。 代碼是:
public class Antlr3JavaLexer extends Lexer {
public static final int PACKAGE=84;
public static final int PUBLIC=87;
public static final int STATIC=90;
public static final int IDENT=164;
public static final int CLASS = 70;
}
現在,我有一個名為hello.java的Java類,它將由ANTLR生成。 代碼就像這個public class hello{ public static void main(String args[]){ System.out.print("Hello World");} }
現在,我創建的ANTLR詞法分析工具的時機已經開始。
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(mainFile.getAbsolutePath())); // Assumption this is to read the hello.class
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final Antlr3JavaLexer lexer = new Antlr3JavaLexer();
try {
lexer.setCharStream(new ANTLRReaderStream(in));
} catch (IOException e) {
e.printStackTrace();
// return false;
}
final CommonTokenStream tokens = new CommonTokenStream();
tokens.setTokenSource(lexer);
Antlr3JavaParser parser = new Antlr3JavaParser(tokens);
System.out.println(tokens + "and" + "\n"); //First Print
System.out.println(tokens.getTokens); // Second Print
幸運的是,我得到這樣的輸出: https : //www.dropbox.com/s/tsogz10eouo9f9h/ID%20Token.bmp
因此,問題是:如何從令牌中獲取ID? 例如, public class hello
是public
= 87, class
= 70, hello
是標識符=164。因此,也許這樣的輸出
8770164
感謝4的幫助...
將對象附加到StringBuilder
(或您可能不應該使用的StringBuffer
)時,它將在對象上調用ToString()
並附加結果文本。 如果要以其他方式設置列表格式,則需要遍歷元素並以所需格式附加文本。
在這種情況下,所需的格式似乎是Token.getType()
。
boolean first = true;
for (Token token : tokens.getTokens()) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(token.getType());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.