我正在寫一個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