I want some grammar to represent a string, quoted by " and the " symbol inside string can be quoted like \". Following is my grammar:
fragment
NUM_LETTER : ('a'..'z'|'A'..'Z'|'0'..'9');
STRING_LITERAL : '"' (NUM_LETTER|'_'|('\\"'))* '"';
But it does not work. I try to interpret "\"a" in AntlrWorks1.5 and it gives a MismatchedTokenException in the generated syntax tree for STRING_LITERAL. Which part of my grammar is wrong?
There's nothing wrong with the grammar. You're probably getting this error because you're using the interpreter, which is buggy. Use ANTLRWorks' debugger instead. The debugger will show you the input "\"a"
is parsed just fine (press CTRL+D to start debugging).
Also, your string rule would probably be better of looking like this:
STRING_LITERAL : '"' (~('"' | '\\' | '\r' | '\n') | '\\' ('"' | '\\'))* '"';
In other words, the contents of your string is zero or more:
~('"' | '\\' | '\r' | '\n')
or
'\\' ('"' | '\\')
Try the following expression:
STRING : '"' (options{greedy=false;}:( ~('\\'|'"') | ('\\' '"')))* '"';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With