Searching basic comments in C++ by regex
Question: I'm writing a Python program for searching comments in c++ program using
regex. I wrote the following code:

    
    
    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)
    

this code should detect comment of type `//I'm comment` and `/*blah blah blah
blah blah*/` I'm getting following output:

    
    
    // my  program in C++
    None
    //use cout
    

Which is I'm not expecting. My thought is match.group(1) should capture the
first parenthesis of `(\/\*(.|\n)*\*\/)`, but it is not. The c++ program I'm
testing is:

    
    
    // my  program in C++
    
    #include <iostream>
    /** I love c++
        This is awesome **/
    using namespace std;
    
    int main ()
    {
      cout << "Hello World"; //use cout
      return 0;
    }
    


Answer: You didn't use the good order to do that since an inline comment can be
include inside a multiline comment. So you need to begin your pattern with the
multiline comment. Example:

    
    
    /\*[\s\S]*?\*/|//.*
    

Note that you can improve this pattern if you have long multiline comments
_(this syntax is an emulation of the atomic group feature that is not
supported by the re module)_ :

    
    
    /\*(?:(?=([^*]+|\*(?!/))\1)*\*/|//.*
    

But note too that there are other traps like a string that contains `/*...*/`
or `//.....`.

So if you want to avoid these cases, for example if you want to make a
replacement, you need to capture before strings and to use a backreference in
the replacement string, like this:

    
    
    (pattern for strings)|/\*[\s\S]*?\*/|//.*
    

replacement: `$1`

