title: Using regex to remove comments from source files
body: <p>I'm making a program to automate the writing of some C code, (I'm writing to parse strings into enumerations with the same name)
  C's handling of strings is not that great.
  So some people have been nagging me to try python.</p>
  <p>I made a function that is supposed to remove C-style <code>/* COMMENT */</code> and <code>//COMMENT</code>
  from a string:
  Here is the code:</p>
  <pre><code>def removeComments(string):
      re.sub(re.compile(&quot;/\*.*?\*/&quot;,re.DOTALL ) ,&quot;&quot; ,string) # remove all occurance streamed comments (/*COMMENT */) from string
      re.sub(re.compile(&quot;//.*?\n&quot; ) ,&quot;&quot; ,string) # remove all occurance singleline comments (//COMMENT\n ) from string
  </code></pre>
  <p>So I tried this code out.</p>
  <pre><code>str=&quot;/* spam * spam */ eggs&quot;
  removeComments(str)
  print str
  </code></pre>
  <p>And it apparently did nothing.</p>
  <p>Any suggestions as to what I've done wrong?</p>
  <p>There's a saying I've heard a couple of times:</p>
  <blockquote>
  <p>If you have a problem and you try to solve it with Regex you end up with two problems.</p>
  </blockquote>
  <hr />
  <p>EDIT:
  Looking back at this years later. (after a fair bit more parsing experience)</p>
  <p>I think regex may have been the right solution.
  And the simple regex used here &quot;good enough&quot;.
  I may not have emphasized this enough in the question.
  This was for a single specific file. That had no tricky situations.
  I think it would be a lot less maintenance to keep the file being parsed simple enough for the regex, than to complicate the regex, into an unreadable symbol soup. (e.g. require that the file only use <code>//</code> single line comments.)</p>