【发布时间】:2018-10-16 00:32:22
【问题描述】:
我必须使用 flex 识别单行和多行注释和字符串。
评论输入示例:
//this is a single line comment
//this is a single \ line comment too
//but this\
is a multi line comment
/* multi line \\n\
comment */
输出应正确识别 cmets。
字符串的示例输入:
"abc"
"abc \\\\ \t \\t def\" "
"abc \\\\ \t \\t def\" \"
"abc
""
"foo \
bar"
"foo \\
bar"
输出应该是:
Line No. 1: Token <STRING> Lexeme "abc" found
Line No. 2: Token <STRING> Lexeme "abc \\\\ \t \\t def\" " found
Error at line 3. Missing terminating character "abc \\\\ \t \\t def\"
\"
Error at line 4. Missing terminating character "abc
Line No. 5: Token <STRING> Lexeme "" found
Line No. 6: Token <STRING> Lexeme "for \
bar" found
Line No. 8. Token <STRING> Lexeme "for \\
bar" found
我还必须处理格式错误/未终止的注释或字符串,这从示例示例中可以明显看出。
如何编写正则表达式来处理这个问题?
我的方法(到目前为止):
NEWLINE \r?\n
STRING \"([^"\n]|\\(.|{NEWLINE}))*\"
这是字符串。我不知道这是否正确。我没有任何评论方法。谁能帮帮我?
【问题讨论】:
-
您需要使用起始状态来处理多行结构。没有它们,您将永远无法正常工作。
标签: regex flex-lexer