Parsing 修改ANTLR中的标记器
在ANTLR中,如何使输出令牌一个接一个地跟随键盘上的“回车”键,我尝试使用一个名为hello.java的类,如下所示Parsing 修改ANTLR中的标记器,parsing,antlr,token,Parsing,Antlr,Token,在ANTLR中,如何使输出令牌一个接一个地跟随键盘上的“回车”键,我尝试使用一个名为hello.java的类,如下所示 public class Hello{ public static void main(String args[]){ System.out.println("Hello World ..."); } } public class Hello { public static ... untill the end... 现在,是解析标记的时候了
public class Hello{
public static void main(String args[]){
System.out.println("Hello World ...");
}
}
public
class
Hello
{
public
static ... untill the end...
现在,是解析标记的时候了
final Antlr3JavaLexer lexer = new Antlr3JavaLexer();
try {
lexer.setCharStream(new ANTLRReaderStream(in)); // in is a file
} catch (IOException e) {
e.printStackTrace();
}
final CommonTokenStream tokens = new CommonTokenStream();
tokens.setTokenSource(lexer);
tokens.LT(10); // force load
Antlr3JavaParser parser = new Antlr3JavaParser(tokens);
System.out.println(tokens);
它给了我这样的输出
publicclassHello{publicstaticvoidmain(Stringarggs[]){System.out.println("Hello World ...");}}
如何使输出看起来像这样
public class Hello{
public static void main(String args[]){
System.out.println("Hello World ...");
}
}
public
class
Hello
{
public
static ... untill the end...
我尝试过使用Stringbuilder,但它不起作用。
感谢4的帮助。您不必只打印令牌,而必须在令牌流上迭代以获得所需的结果 像这样修改代码
final Antlr3JavaLexer lexer = new Antlr3JavaLexer();
try {
lexer.setCharStream(new ANTLRReaderStream(in)); // in is a file
} catch (IOException e) {
e.printStackTrace();
}
final CommonTokenStream tokens = new CommonTokenStream();
tokens.setTokenSource(lexer);
//tokens.LT(10); // force load - not needed
Antlr3JavaParser parser = new Antlr3JavaParser(tokens);
// Iterate over tokenstream
for (Object tk: tokens.getTokens())
{
CommonToken commontk = (CommonToken) tk;
if (commontk.getText() != null && commontk.getText().trim().isEmpty() == false)
{
System.out.println(commontk.getText());
}
}
在此之后,您将得到此结果
public
class
Hello
{
public
static ... etc...
希望这能解决您的问题。谢谢4 Mohit Chawda,愿上帝保佑您。这对我帮助很大。如何获得输出将被抛出到JtextArea这是代码:`for(Object tk:tokens.getTokens()){CommonToken commontk=(CommonToken)tk;if(commontk.getText()!=null&&commontk.getText().trim().isEmpty()=false){System.out.println(commontk.getText());StringBuilder sb=new StringBuilder(commontk.getText());TextArea.setText(“\n”+sb.toString());}}}`它只是给我最后的标记。不是所有的标记。谢谢@Mohit ChawdaYou实际上正在为循环创建一个新的StringBuilder。初始化它一次。另外,去掉TextArea代码。在for循环之后设置文本。希望你明白。嗨,Mohit,看看这个: