我正在写一个Python程序,用于使用正则表达式在C++程序中搜索注释。 我写了下面的代码:用正则表达式在C++中搜索基本注释
import re
regex = re.compile(r'(\/\/(.*?))\n|(\/\*(.|\n)*\*\/)')
comments = []
text = ""
while True:
try:
x= raw_input()
text = text + "\n"+ x
except EOFError:
break
z = regex.finditer(text)
for match in z:
print match.group(1)
此代码应检测//I'm comment
类型和/*blah blah blah blah blah*/
我得到以下输出的评论:
// my program in C++
None
//use cout
这是我不期待。我的想法是match.group(1)应该捕获第一个括号(\/\*(.|\n)*\*\/)
,但事实并非如此。 C++的程序,我测试的是:
// my program in C++
#include <iostream>
/** I love c++
This is awesome **/
using namespace std;
int main()
{
cout << "Hello World"; //use cout
return 0;
}
在我的情况下,这些陷阱是不可能的:) – Dheerendra 2014-11-14 21:56:39
@Dheerendra:所以你只需要简单的答案。 – 2014-11-14 21:57:42