2017-02-20 59 views
2

這裏是我試過的代碼,Python程序刪除C類單個和多個行註釋

from re import * 


commentStart = compile('/\*') 
commentEnd = compile('\*/') 
singleComment = compile('//') 
quotes = compile('".*"') 

def readComment(line): 

    while(line): 
     if(commentEnd.match(line)): 
      return 
     line = input() 

line=input() 

while(line): 
    if(quotes.match(line)): 
     print(line) 
     line = input() 
     continue 

    elif(commentStart.match(line)): 

     readComment(line) 
     line=input() 
     continue 

    elif(singleComment.match(line)): 
     line=input() 
     continue 

    else: 
     print(line) 

    line=input() 

我能刪除單行註釋,但我有與多行註釋的問題。

樣品輸入:

abcd 
//blah 
efg 
/*blah 
blah 
blah*/ 
hij 

我的輸出:

abcd 
efg 

預期輸出:

abcd 
efg 
hij 

請指出,我做了錯誤。謝謝。

+1

因此,如果您收到答案,您可以使用您應該將其標記爲已接受。 –

回答

4

這一個:

commentEnd.match(line) 

應該是:

commentEnd.search(line) 

docs

如果你想在字符串的任何地方找到一個匹配,使用搜索()改爲

+0

謝謝!現在正在工作。 – coder123