Replace token in ANTLR

偶尔善良 提交于 2019-12-04 17:27:30

Rewrite the text inside the lexer:

SingleLineComment
 : '//' ~('\r' | '\n')* {setText("replacement");}
 ;

EDIT

Okay, here's a quick demo how you can filter certain tokens from a language:

SingleCommentStrip.g

grammar SingleCommentStrip;

parse returns [String str]
@init{StringBuilder builder = new StringBuilder();}
 : (t=. {builder.append($t.text);})* EOF {$str = builder.toString();}
 ;

SingleLineComment
 : '//' ~('\r' | '\n')* {skip();}
 ;

MultiLineComment
 : '/*' .* '*/'
 ;

StringLiteral
 : '"' ('\\' . | ~('"' | '\\' | '\r' | '\n'))* '"'
 ;

AnyOtherChar
 : .
 ;

Main.java

import org.antlr.runtime.*;

public class Main {
  public static void main(String[] args) throws Exception {
    SingleCommentStripLexer lexer = new SingleCommentStripLexer(new ANTLRFileStream("Test.java"));
    SingleCommentStripParser parser = new SingleCommentStripParser(new CommonTokenStream(lexer));
    String adjusted = parser.parse();
    System.out.println(adjusted);
  }
}

Test.java

// COMMENT
class Test {
  /*
  // don't remove
  */
  // COMMENT AS WELL
  String s = "/* don't // remove */ \" \\ me */ as well";
}

Now run the demo:

java -cp antlr-3.3.jar org.antlr.Tool SingleCommentStrip.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main

which will print:


class Test {
  /*
  // don't remove
  */

  String s = "/* don't // remove */ \" \\ me */ as well";
}

(i.e. the single line comments are removed)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!