使用Antlr4的TokenStreamRewriter修改内容
需求:在css中利用变量控造部门属性的值
项目中设置装备摆设antlr版本<dependency> <groupId>org.antlr</groupId> <artifactId>antlr4-runtime</artifactId> <version>4.9.3</version> </dependency> 利用官方css.g4 demo生成api$ antlr4 -no-listener -visitor css.g4利用TokenStreamRewriter修改package css; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.TokenStreamRewriter; import org.antlr.v4.runtime.tree.ParseTree; public class Css { public static void main(String[] args) { CssLexer lexer = new CssLexer(CharStreams.fromString(".b { color: red; } .c { color: blue; }")); CommonTokenStream stream = new CommonTokenStream(lexer); CssParser parser = new CssParser(stream); ParseTree tree = parser.stylesheet(); EvalVisitor evalVisitor = new EvalVisitor(stream); evalVisitor.visit(tree); System.out.println(evalVisitor.rewriter.getText()); } } class EvalVisitor extends CssBaseVisitor<String> { TokenStreamRewriter rewriter; public EvalVisitor(CommonTokenStream tokenStream) { rewriter = new TokenStreamRewriter(tokenStream); } @Override public String visitExpr(CssParser.ExprContext ctx) { String text = ctx.getText(); if (text.equals("red")) { rewriter.replace(ctx.getStart(), ctx.getStop(), "#ff0000"); } return super.visitExpr(ctx); } }完好代码:https://github.com/schizobulia/antlr4_demo/blob/main/src/main/java/css/Css.java
目前我司
在招高级前端、ios、android开发(完全长途)。大佬们有兴趣的发简历
邮箱:MjgzMzMyNDUyOEBxcS5jb20=若是你喜好我的做品,请考虑赞助我,以连结它们的可持续性。
0