simplest way to strip a comment from the end of a line?

eric eric at
Thu Dec 4 17:15:47 CET 2008

On Dec 4, 4:50 pm, Joe Strout <j... at> wrote:
> I have lines in a config file which can end with a comment (delimited  
> by # as in Python), but which may also contain string literals  
> (delimited by double quotes).  A comment delimiter within a string  
> literal doesn't count.  Is there any easy way to strip off such a  
> comment, or do I need to use a loop to find each # and then count the  
> quotation marks to its left?
> Thanks,
> - Joe


if the string literal you wan't to escape, is not escaped (i.e
contains \" ) then a regexp like

.*?(?:".*?".*?)*#(?P<comment> .*?)$

(not tested)
.*?  everything but keep it greedy
".*?" the string literal not escaped

More information about the Python-list mailing list