Python: Replacing a newline with a space between multiline comments
Question: I am relatively new to python and i need to print the multiline comments used
in the C program. I have a test.c file which is as below:

    
    
    /* print multiline
    
       comments */
    

I tried the following python code to parse the C code and print the multiline
comments

    
    
    import re 
    
    fileopen = open('test.c', 'rw')
    
    for var in fileopen:
        if var.startswith("/*"):
            var1 = re.sub(r'\n', " ", var)
            var1 = var.rstrip()
            print var1
    

The output I get is:

    
    
    /* print multiline
    

The second line of the comment does not get printed even if I substitute
newline with a space. Please help me in this regard.


Answer: If your only requirement is finding comments that span multiple lines, thats
actually quite easy. Like so:

    
    
    for match in re.finditer(r"\/\*(.*\n.*)\*\/", code, re.MULTILINE):
        print match.group(1)
    

The important part is:

    
    
    \/\*(.*\n.*)\*\/
    

Which finds a literal `/*`, any number of characters, a newline, any number of
characters and a literal `*/`, and captures the parts between the comment
delimiters.

Additionally, the flag
[`re.MULTILINE`](https://docs.python.org/2/library/re.html#re.MULTILINE)
allows the regex search to search across lines, which allows us to enforce
that it _must_ be a multiline comment.

The [full code can be run on codepad.org](http://codepad.org/NscedCDT):

    
    
    code= """/* print multiline
       comments */
    
    // One line comment
    /* Another one line comment */
    
    /* Multiline
       comment */
    """
    
    import re
    
    for match in re.finditer(r"\/\*(.*\n.*)\*\/", code, re.MULTILINE):
        print match.group(1)
    

Which gives:

    
    
    print multiline
      comments 
    Multiline
      comment 
    

