1

我有一个带有 python doctest 的函数,该函数失败,因为其中一个测试输入字符串有一个反斜杠,即使我已将字符串编码为原始字符串,它也被视为转义字符。

我的 doctest 看起来像这样:

>>> 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']

该函数旨在根据待办事项规范的一些变化从单行中提取待办事项文本,如下所示:

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

并且调用的正则表达式todo_match_obj是:

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

与我的 ipython shell 的快速对话给了我:

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

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

而且,以防万一 doctest 实现使用标准输出(我没有检查,抱歉):

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

从任何标准来看,我的 regex-foo 都不高,我意识到我可能在这里遗漏了一些东西。

编辑:在 Alex Martellis 回答之后,我想就什么正则表达式实际匹配 blasted 的建议提出建议r"""//\todo fix me"""。我知道我最初并没有要求别人做我的作业,我会接受亚历克斯的回答,因为它确实回答了我的问题(或证实了我的恐惧)。但我保证在这里为我的问题投票任何好的解决方案:)

编辑编辑:作为参考,已在 kodos 项目中提交了一个错误:错误 #437633

我正在使用 Python 2.6.4(r264:75706,2009 年 12 月 7 日,18:45:15)

谢谢你读到这里(如果你直接跳过这里,我明白)

4

2 回答 2

2

仔细阅读您的原始正则表达式:

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

它匹配:零到两个斜杠,然后是 0+ 个星号,然后是 0 或 1 个“空白字符”(空格、制表符等),然后是文字字符'todo'(等等)。

你的原始字符串是:

r"""//\todo      stuff to fix"""

所以斜杠和 之间有一个文字反斜杠'todo',因此正则表达式当然不匹配它。它不能——在那个正则表达式中,你没有表达任何选择匹配文字反斜杠的愿望。

编辑:一个 RE 模式,非常接近你的,它接受并忽略一个可选的反斜杠,然后't'是:

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

请注意,在这种情况下,必须重复反斜杠才能“自行转义”

于 2010-04-05T19:44:52.423 回答
1

当我在 doctests 的道路上冒险时,这变得更加奇怪。

考虑这个python 脚本

如果取消注释第 22 行和第 23 行,脚本会顺利通过,因为方法返回True,它既被断言又被显式比较。

但是,如果您在链接中运行该文件,则 doctest 将失败并显示以下消息:

% python doctest_test.py                                                                                                          
**********************************************************************
File "doctest_test.py", line 3, in __main__.doctest_test
Failed example:
    doctest_test( r"""//    odo""" )
Exception raised:
    Traceback (most recent call last):
      File "/usr/lib/python2.6/doctest.py", line 1241, in __run
        compileflags, 1) in test.globs
      File "<doctest __main__.doctest_test[0]>", line 1, in <module>
        doctest_test( r"""//    odo""" )
      File "doctest_test.py", line 14, in doctest_test
        assert input_string == compare_string
    AssertionError
**********************************************************************
1 items had failures:
   1 of   1 in __main__.doctest_test
***Test Failed*** 1 failures.

有人可以在这里启发我吗?

为此,我仍在使用 python 2.6.4。

我将这个答案放在“社区 wiki”下,因为它在声誉方面确实与问题无关。

于 2010-04-05T21:41:42.197 回答