Passing string with (accidental) escape character loses character even though it's a raw string

Posted by Steen on Stack Overflow See other posts from Stack Overflow or by Steen
Published on 2010-04-05T19:36:38Z Indexed on 2010/04/05 20:13 UTC
Read the original article Hit count: 392

I have a function with a python doctest that fails because one of the test input strings has a backslash that's treated like an escape character even though I've encoded the string as a raw string.

My doctest looks like this:

>>> infile = [ "Todo:        fix me", "/** todo: fix", "* me", "*/", r"""//\todo      stuff to fix""", "TODO fix me too", "toDo bug 4663" ]
>>> find_todos( infile )
['fix me', 'fix', 'stuff to fix', 'fix me too', 'bug 4663']

And the function, which is intended to extract the todo texts from a single line following some variation over a todo specification, looks like this:

todos = list()
for line in infile:
    print line
    if todo_match_obj.search( line ):
        todos.append( todo_match_obj.search( line ).group( 'todo' ) )

And the regular expression called todo_match_obj is:

r"""(?:/{0,2}\**\s?todo):?\s*(?P<todo>.+)"""

A quick conversation with my ipython shell gives me:

In [35]: print "//\todo"
//      odo

In [36]: print r"""//\todo"""
//\todo

And, just in case the doctest implementation uses stdout (I haven't checked, sorry):

In [37]: sys.stdout.write( r"""//\todo""" )
//\todo

My regex-foo is not high by any standards, and I realize that I could be missing something here.

EDIT: Following Alex Martellis answer, I would like suggestions on what regular expression would actually match the blasted r"""//\todo fix me""". I know that I did not originally ask for someone to do my homework, and I will accept Alex's answer as it really did answer my question (or confirm my fears). But I promise to upvote any good solutions to my problem here :)

I'm using Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)

Thank you for reading this far (If you skipped directly down here, I understand)

© Stack Overflow or respective owner

Related posts about python

Related posts about doctest