| Refresh | Home EGTry.com

nested code blocks


Input

 { hello; { a=2; b=3; } }  {}  {c=a+b}


Output

0: (5,# #)
1: (4,#{ hello; { a=2; b=3; } }#)
2: (5,# #)
3: (5,# #)
4: (4,#{}#)
5: (5,# #)
6: (5,# #)
7: (4,#{c=a+b}#)


antlr grammar

lexer grammar L1;

//INPUT: { hello; { a=2; b=3; } }  {}  {c=a+b}

Block: '{' (Block | ~('{' | '}') )* '}';

Any: .;





java code that use the lexer

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.Token;



public class L1Main {
    public static void main(String[] args) throws Exception {
    	ANTLRStringStream input=new ANTLRStringStream(" { hello; { a=2; b=3; } }  {}  {c=a+b}");
    	L1 lexer = new L1(input);
    	int i=0;
    	Token token;   	
    	while(  (token=lexer.nextToken()).getType() !=Token.EOF) {
    		
    		System.out.println(i+++": ("+token.getType()+",#"+token.getText()+"#)");
    	}
        
    }
}