Python 2.7.1的re模块中带有re.split函数和re.DOTALL标志的错误


问题内容

我有一台运行Lion和Python 2.7.1的Mac。我注意到re模块中有些非常奇怪的东西。如果我运行以下行:

print re.split(r'\s*,\s*', 'a, b,\nc, d, e, f, g, h, i, j, k,\nl, m, n, o, p, q, r')

我得到这个结果:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r']

但是,如果我使用re.DOTALL标志运行它,如下所示:

print re.split(r'\s*,\s*', 'a, b,\nc, d, e, f, g, h, i, j, k,\nl, m, n, o, p, q, r', re.DOTALL)

然后我得到这个结果:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q, r']

请注意,“ q,r”被视为一次匹配,而不是两次。

为什么会这样呢?我不明白为什么如果我不在图案中使用点,re.DOTALL标志会有所作为。我是在做错什么还是有某种错误?


问题答案:
>>> s = 'a, b,\nc, d, e, f, g, h, i, j, k,\nl, m, n, o, p, q, r'
>>> re.split(r'\s*,\s*', s)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r']
>>> re.split(r'\s*,\s*', s, maxsplit=16)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q, r']
>>> re.split(r'\s*,\s*', s, flags=re.DOTALL)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r']

问题在于您要按re.DOTALL位置传递maxsplit=0参数,而不是flags=0参数。 re.DOTALL碰巧是常数16