Given a String like..
(a+(a+b)), (d*e) :- (e-f)
Note: (d*e) and (e-f) are different expressions. How can I fetch the expressions from this string. I have the grammar defined as..
parse returns [String value]
: addExp {$value=$addExp.value;} EOF
;
addExp returns [String value]
: multExp {$value=$multExp.value;} (('+' | '-' | '*') multExp{$value+= '+' + $multExp.value;})*
;
multExp returns [String value]
: atom {$value=$atom.value;} (('*' | '/') atom {$value+=$atom.value;)*
;
atom returns [String value]
: x=ID {$value=$x.text;}
| '(' addExp ')' {$value='('+$addExp.value+')';}
;
ID : 'a'..'z' | 'A'..'Z';
I tried..
ANTLRStringStream a=new ANTLRStringStream("(a+(a+b)), (d*e) :- (e-f)");
SLexer l=new SLexer(a);
CommonTokenStream c=new CommonTokenStream(l);
SParser p=new Sparser(c);
String exp;
while(exp = p.parse())
{
System.out.println(exp);
}
I’m thinking of something like hasNext() and then fetching.
Your lexer rules
TEXTpossibly matches an empty string, causing the lexer to create an infinite amount of tokens. Also, you don’t need all thosereturnstatements after your rule: you can simply grab what a parser (or lexer) rule matched by adding.textafter it.You could let your parser return a
List<String>, or let it return a singleStringrepeatedly invoke that parser rule untilEOFis encountered.A little demo:
Note that
~TEXT+in theparserule matches one or more tokens other thanTEXT.If you now create a lexer and parser and run the
TParserclass:*nix/MacOS
or
Windows
you will see the following being printed to your console:
EDIT
And here’s how to return a single
Stringopposed to aList<String>: