ANTLR4 - 需要对此字符串文字的解释 [英] ANTLR4 - Need an explanation on this String Literals

查看:24
本文介绍了ANTLR4 - 需要对此字符串文字的解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的作业中,我有关于字符串词法分析器的描述:

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

"字符串字面量包含零个或多个由 double 括起来的字符引号 (").使用转义序列(如下所列)表示特殊字符串中的字符.这是一个新行的编译时错误或出现在字符串文字中的 EOF 字符.

"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 退格

\f 换页

\r 回车

\n 换行

\t 水平制表符

\" 双引号

\反斜杠

以下是字符串文字的有效示例:

The following are valid examples of string literals:

"这是一个包含制表符\t的字符串"

"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'))*'"';

有人可以检查我的词法分析器是否符合要求吗?如果不是,请告诉我您的更正,我不太了解要求和ANTLR4.

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.

推荐答案

使用ANTLR4,不用写\\ ('b' | 't' | 'n'),你可以写<代码>\\ [btn].此外,正如 J Earls 在评论中提到的,您需要在否定集中包含引号,以及 \r 和文字 \.

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 \.

这应该可以解决问题:

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

这篇关于ANTLR4 - 需要对此字符串文字的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆