【问题标题】:Flex regular expression literal charFlex 正则表达式文字字符
【发布时间】:2013-03-11 03:23:48
【问题描述】:

我在使用 flex 设置正则表达式以匹配类似 C 的文字字符时遇到了一些麻烦。

我需要根据语法匹配正确的文字字符和不正确的文字字符,例如未终止的字符文字。

2 条规则,一条用于正确规则,一条用于未终止规则。

chrlit          (\')([^\\\'\n]|(\\.))(\')
untermchrlit    (\')([\\|\']|(.))*

我需要关于正则表达式的帮助,因为它们没有按我的需要工作。下面是一些示例,它们应该如何工作:

'          -> unterminated char constant
'/'        -> CHRLIT('/')
'('        -> CHRLIT('(')
'a"b"c"de  -> unterminated char constant
'abc       -> unterminated char constant
'abc\      -> unterminated char constant
'\\'       -> CHRLIT('\\')
';'        -> CHRLIT(';')
''         -> unterminated char constant
'a'        -> CHRLIT('a')
'\'        -> unterminated char constant 
'\;'       -> CHRLIT('\;')
'\\\'      -> unterminated char constant
'\\\       -> unterminated char constant    
'\/'       -> CHRLIT('\/')
'a\'       -> unterminated char constant
'\\        -> unterminated char constant
'\t'       -> CHRLIT('\t')

【问题讨论】:

  • @MikeM 这是一个字符文字,所以只有一个字符。我有另一条规则来匹配多字符常量,因此它们会给出错误,但我认为它与问题无关;)
  • @MikeM 我的 untermchrlit 在 '\'、'a\'、''' 和其他一些情况下都失败了。它给了我奇怪的结果..
  • @MikeM 怎么做?

标签: regex cygwin expression flex-lexer


【解决方案1】:

问题在于,您的未终止字符文字模式也将匹配终止字符以及任何后续字符,除非字符文字位于行尾。与其尝试精确匹配未终止的字符文字,不如像这样让自己的生活更简单,如果遇到' 而不是chrlit 的开头,则返回到untermchrlit。 (所以它必须是未终止的,如果chrlit 匹配所有可能的终止文字。)(我还冒昧地从您的正则表达式中删除了所有多余的括号和反斜杠,这使得它们读起来不那么嘈杂。 )

chrlit          '([^'\\\n]|\\.)'
untermchrlit    '

此解决方案的唯一问题是它会在未终止的' 之后立即继续扫描,这很可能会造成人为错误,特别是在确实存在匹配的' 的情况下,如@ 987654328@。在这里,您真的想在第二个 ' 之后继续进行词法扫描(实际上,您可能希望将其标记为过长的字符文字而不是未终止的文字)。要处理这种情况,您需要一组更复杂的模式。以下是可能性:

/* As before */
chrlit          '([^'\\\n]|\\.)'
/* Also as before, a catch-all case. */
untermchrlit    '
/* Try to match single-quoted strings which are too short or too long */
emptychrlit     ''
/* The action for this regex *must* come after the action for chrlit */
longchrlit      '([^'\\\n]|\\.)+'

我应该注意到这里的longchrlit 也匹配chrlit 匹配的所有内容,但与OP 中的模式不同,它不再匹配任何字符。重要的是按照注释指示对操作进行排序,以便chrlit 匹配正确的文字。 (如果你弄错了顺序,flex 应该会发出警告。)

请记住,Flex 始终匹配 最长 匹配项,但如果多个规则与完全相同的标记匹配,Flex 会选择 first 操作。

顺便说一句,至少在 C 中,以下 一个有效的字符文字:

'a\
'

这是因为 \ 后面紧跟一个换行符已从输入中完全删除,因此第二个 ' 的词法分析就像紧跟在 a 之后一样。

【讨论】:

    猜你喜欢
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多