antlr match any character except

Andrey picture Andrey · Feb 14, 2013 · Viewed 13.4k times · Source

I have the following deffinition of fragment:

fragment CHAR   :'a'..'z'|'A'..'Z'|'\n'|'\t'|'\\'|EOF;  

Now I have to define a lexer rule for string. I did the following :

STRING   : '"'(CHAR)*'"'

However in string I want to match all of my characters except the new line '\n'. Any ideas how I can achieve that?

Answer

Bart Kiers picture Bart Kiers · Feb 14, 2013

You'll also need to exclude " besides line breaks. Try this:

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

The ~ negates char-sets.

ut I want to negate only the new line from my CHAR set

No other way than this AFAIK:

STRING : '"' CHAR_NO_NL* '"' ;

fragment CHAR_NO_NL : 'a'..'z'|'A'..'Z'|'\t'|'\\'|EOF;