2017-09-26 66 views
2
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初始分裂没有回升,但回升的时候你拆pieces[4]蟒蛇re.split不工作的所有领域

+0

只要使用're.split(r'(?i)(错误在字段:)',字符串)' – kaza

回答

5

re.split位置参数是:

  • 正则表达式
  • maxsplit(默认值:无限制)
  • 标志(初始值:无标志)

    split(pattern, string, maxsplit=0, flags=0)

您正在通过re.IGNORECASE(该标志的值为2)为maxsplit参数(如postional),它解释了奇怪的影响。它在某种程度上起作用,然后在2次分裂后按照指示停止分裂。

只要做flags=re.IGNORECASE(关键字,而不是位置),而不是它的工作原理。

re.compile可以传递标志的位置安全:compile(pattern, flags=0),并且对于re.matchre.search是真的为好,但不适合re.split & re.sub,所以它是一个简单的陷阱掉进去。如有疑问,请始终为可选参数使用传递关键字。

2

您需要使用re.split时注明要使用flags=明确使用标志:

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, flags=re.I) 

print(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\n', 'Error on the field:', ' final lines'] 

注:re.Ire.IGNORECASE相同