Python 2.7.1 的 re 模块中带有 re.split 函数和 re.DOTALL 标志的错误 [英] Bug with re.split function and re.DOTALL flag in re module of Python 2.7.1

查看:54
本文介绍了Python 2.7.1 的 re 模块中带有 re.split 函数和 re.DOTALL 标志的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Mac running Lion and Python 2.7.1. I am noticing something very strange from the re module. If I run the following line:

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 标志运行它:

But if I run it with the re.DOTALL flag like this:

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' 被视为一个匹配项,而不是两个.

Note that 'q, r' is counted as one match instead of two.

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

Why is this happening? I don't see why the re.DOTALL flag would make a difference if I am not using dots in my pattern. Am I doing something wrong or is there some sort of bug?

推荐答案

>>> 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.

The problem is that you are passing re.DOTALL positionally, where it sets the maxsplit=0 argument, not the flags=0 argument. re.DOTALL happens to be the constant 16.

这篇关于Python 2.7.1 的 re 模块中带有 re.split 函数和 re.DOTALL 标志的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆