【问题标题】:Regular expression for comment and string in flexflex中注释和字符串的正则表达式
【发布时间】: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


【解决方案1】:

我不认为编写单个 RE 来涵盖所有可能的情况是一个好主意(甚至可能)。试试这样的方法怎么样:

用于匹配字符串

  • 多行字符串"(([^\n]|\\\n)*)(?&lt;!\\)"
  • 格式错误的字符串"(.*)((?&lt;=\\)"|[^"\\])$

(使用lookarounds消除或包含转义引号,您可以阅读更多here

用于匹配 cmets

  • 带有 // ^\/\/((\\\n)|[^\n])* 的单行和多行注释
  • 带有 /* */ ^\/\*(.*)\*\/ 的多行注释(此注释必须在启用“点匹配新行”选项的情况下运行)

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2017-03-20
    • 2013-03-11
    相关资源
    最近更新 更多