python re.split 不适用于所有领域

标签 python regex split

import re
string = "some text \n\n\nError on the field: more\n text and lines\n\n\nError on the field: some more\n lines \n\n\nError on the field: final lines"
pieces = re.split(r'(Error on the field:)', string, re.IGNORECASE)
pieces
['some text \n\n\n', 'Error on the field:', ' more\n text and lines\n\n\n', 'Error on the field:', ' some more\n lines \n\n\nError on the field: final lines']
pieces2 = re.split(r'(Error on the field:)', pieces[4], re.IGNORECASE)
pieces2
[' some more\n lines \n\n\n', 'Error on the field:', ' final lines']

为什么 'Error on the field:' 的第三次拆分没有在 pieces 的初始拆分中被拾取,但在拆分时被拾取 件[4]?

最佳答案

re.split 的位置参数是:

  • 正则表达式
  • 字符串
  • 最大拆分(默认值:无限制)
  • 标志(默认值:无标志)

    split(模式, 字符串, maxsplit=0, flags=0)

您正在传递 re.IGNORECASE(标志的值为 2)作为 maxsplit 参数(作为 postional) 这解释了奇怪的效果。它在一定程度上起作用,然后在 2 次拆分后按照指示停止拆分。

只需执行 flags=re.IGNORECASE(关键字,而不是位置)即可。

re.compile 中,您可以将该标志作为位置安全地传递:compile(pattern, flags=0),对于 re.match< 也是如此re.search,但不是 re.splitre.sub,所以很容易落入陷阱.如有疑问,请始终对可选参数使用关键字传递。

关于python re.split 不适用于所有领域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46434156/

相关文章:

python - 为什么可以在 python 3 中使用 ctypes 修改不可变字节对象?

php - 删除 perso-arabic 字符串中的隐藏空格

css - 如何缩放背景图像

Javascript 解析聊天文本

javascript - 在 JavaScript 中从字符串中拆分数字

python - 使用 Flask-Assets 编译 less 文件的问题

python - 如何将 networkx (python) 节点序列化为 json 格式?

python - 如何以更好和更短的方式获得相同的所需字符串

javascript - 验证按键上的日期不起作用

java - 使用RegEx替换eclipse中的行