2017-02-20 32 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