2012-11-26 44 views
0

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

因为我需要找出所有的评论给定的输入文件:

//.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])* 
(.)*"\*\/" 

我不明白为什么多在线评论没有被匹配?有人可以提供一些见解吗?

回答

3

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

通常的正则表达式的C风格的评论是:

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

这个匹配0个或多个“任何东西,除了*”或“1个或多个* S后面没有*或/”里面的评论标记。

0

c或C++程序中注释的正则表达式如下所示: “//”。 |“/”(。[\ n]。 /”