<p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p>

<p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p>

<p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>

C (and C++) comments cannot be nested. Regular expressions work well:
```
```
//.*?\n|/\*.*?\*/
```
```
This requires the “Single line” flag (
```
Re.S
```
) because a C comment can span multiple lines.
```
```
def stripcomments(text):
    return re.sub('//.*?\n|/\*.*?\*/', '', text, flags=re.S)
```
```
This code should work.
/EDIT: Notice that my above code actually makes an assumption about line endings! This code won't work on a Mac text file. However, this can be amended relatively easily:
```
```
//.*?(\r\n?|\n)|/\*.*?\*/
```
```
This regular expression should work on all text files, regardless of their line endings (covers Windows, Unix and Mac line endings).
/EDIT: MizardX and Brian (in the comments) made a valid remark about the handling of strings. I completely forgot about that because the above regex is plucked from a parsing module that has additional handling for strings. MizardX's solution should work very well but it only handles double-quoted strings.