ANTLR4 - Need an explanation on this String Literals

只愿长相守 提交于 2019-12-25 07:39:20

问题


On my assignment, I have this description for the String Lexer:

"String literals consist zero or more characters enclosed by double quotes ("). Use escape sequences (listed below) to represent special characters within a string. It is a compile-time error for a new line or EOF character to appear inside a string literal.

All the supported escape sequences are as follows:

\b backspace

\f formfeed

\r carriage return

\n newline

\t horizontal tab

\" double quote

\ backslash

The following are valid examples of string literals:

"This is a string containing tab \t"

"He asked me: \"Where is John?\""

A string literal has a type of string."

And this is my String lexer:

STRINGLIT: '"'(('\\'('b'|'t'|'n'|'f'|'r'|'\"'|'\\'))|~('\n'))*'"';

Can anybody check for my lexer if it meets the requirement or not? If it's not, please tell me your correction, I don't really understand the requirement and ANTLR4.


回答1:


With ANTLR4, instead of writing \\ ('b' | 't' | 'n'), you can write \\ [btn]. Also, as J Earls mentioned in a comment, you'll want to include the quote in your negated set, as well as the \r and the literal \.

This ought to do the trick:

STRINGLIT
 : '"' ( '\\' [btnfr"'\\] | ~[\r\n\\"] )* '"'
 ;


来源:https://stackoverflow.com/questions/39348288/antlr4-need-an-explanation-on-this-string-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!