Search code examples
stringantlrantlr4apostrophe

ANTLRv4 - How to identify unquoted quote within string


How would I recognise the string "Aren't you a string?" without getting a token recognition error at the apostrophe?

Here is the relative grammar from my lexer:

STRING_LITERAL : '"' STRING? '"';
fragment STRING : STRING_CHARACTER+;  
fragment STRING_CHARACTER :  ~["'\\] | ESCSEQ;
fragment ESCSEQ : '\\' [tnfr"'\\];

Solution

  • Remove the single quote from ~["'\\]:

    STRING_LITERAL : '"' STRING? '"';
    fragment STRING : STRING_CHARACTER+;  
    fragment STRING_CHARACTER :  ~["\\] | ESCSEQ;
    fragment ESCSEQ : '\\' [tnfr"'\\];