Eli*_*ria 7 python regex python-2.7
我有一台运行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')
Run Code Online (Sandbox Code Playgroud)
我得到这个结果:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r']
Run Code Online (Sandbox Code Playgroud)
但是,如果我使用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)
Run Code Online (Sandbox Code Playgroud)
然后我得到这个结果:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q, r']
Run Code Online (Sandbox Code Playgroud)
请注意,'q,r'计为一个匹配而不是两个匹配.
为什么会这样?我不明白为什么如果我在模式中没有使用点,则re.DOTALL标志会有所不同.我做错了什么还是有某种错误?
eph*_*ent 13
>>> 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']
Run Code Online (Sandbox Code Playgroud)
问题是你在re.DOTALL位置上传递,它设置maxsplit=0参数,而不是flags=0参数. re.DOTALL碰巧是常数16.
| 归档时间: |
|
| 查看次数: |
1537 次 |
| 最近记录: |