【问题标题】:Complete Comments REGEX for LEX为 LEX 完成评论正则表达式
【发布时间】:2012-11-26 17:17:51
【问题描述】:

我正在使用 Lex 和 Yacc 构建一个计算器编译器。该想法基于以下资源:http://epaperpress.com/lexandyacc/index.html

对于给定的输入文件,我需要识别所有的 cmets:

//.TEST -- JWJ
//.Step final  -- testing all requirements
//.source: test-1m.cal
//.expected output: test-1m_expected.out

/**
 *  This program will use Newton's method to estimate the roots of


 This should be a comment as well, but does not get picked up


 *  f(x) = x^3 - 3*x 
 */
 float xn;
 float xo;
// int num_iterations;
 xo = 3.0;
 xn = 3.0;
 num_iterations = 1;

 /* A do-while loop */
 do {
  print xo;
  xo = xn;
  xn = xo - ( xo * xo * xo - 3.0 * xo  ) / ( 3.0 * xo * xo - 3.0);
  num_iterations = num_iterations + 1;
} while ( num_iterations <= 6 )

print xn; // The root found using Newton's method.
print (xo * xo * xo - 3.0 * xo ); // Print f(xn), which should be 0.

我在我的 lex 文件中使用以下正则表达式:

"//"[^\n]*|"\/\*".*"\*\/"
"\/\*"([^\n])*  
(.)*"\*\/"  

我不明白为什么没有匹配多行 cmets?有人可以提供一些见解吗?

【问题讨论】:

    标签: regex compiler-construction bison lex


    【解决方案1】:

    flex 中的. 字符匹配除换行符以外的任何字符(因此它与[^\n] 相同)。因此,您的正则表达式都不匹配任何包含换行符的注释。

    C 风格注释的常用正则表达式是:

    "/*"([^*]|\*+[^*/])*\*+"/"
    

    这匹配注释标记内的 0 个或多个“除 * 之外的任何内容”或“1 个或多个 *s 后不跟 * 或 /”。

    【讨论】:

    • 所以模式说:它应该以 /* 开头并以 / 结尾。可以有任何 *s 但不应该有 */。[^]表示不允许 *s,但它已由左侧的 *+ 说明。因此新行将被此识别。
    【解决方案2】:

    C 或 C++ 程序中 cmets 的正则表达式如下:

    "//".*|"/*"(.*[\n].*)*"*/"

    【讨论】:

    • 这甚至不匹配/* */
    猜你喜欢
    • 1970-01-01
    • 2015-04-09
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 2017-01-10
    • 2012-08-18
    相关资源
    最近更新 更多