通过文本中的特定行在Python中拆分字符串

时间:2015-01-03 06:13:11

标签: python regex

如果有一行只包含" ----"我想分割一段文本。我使用re.split(..)方法,但它的行为不符合预期。我错过了什么?

import re

s = """width:5
----
This is a test sentence to test the width thing"""

print re.split('^----$', s)

这只是打印

['width:5\n----\nThis is a test scentence to test the width thing']

5 个答案:

答案 0 :(得分:3)

您错过了MULTILINE flag

print re.split(r'^----$', s, flags=re.MULTILINE)

没有它^$应用于整个s字符串,而不是字符串中的每一行:

  

re.MULTILINE

     

指定时,模式字符' ^'比赛开始时   字符串和每行的开头(紧随其后)   每个换行符);和模式字符' $'比赛结束时   字符串和每行的末尾(紧接在每行之前)   换行)。

演示:

>>> import re
>>> 
>>> s = """width:5
... ----
... This is a test sentence to test the width thing"""
>>> 
>>> print re.split(r'^----$', s, flags=re.MULTILINE)
['width:5\n', '\nThis is a test sentence to test the width thing']

答案 1 :(得分:0)

此外,您不能使用^$,因为您使用^$指定正则表达式引擎从字符串的第一个到结尾匹配,并使用{{ 3}}保持\n

>>> print re.split('(?<=\n)----(?=\n)', s)
['width:5\n', '\nThis is a test sentence to test the width thing']

答案 2 :(得分:0)

另一种不使用正则表达式进行拆分的方法。

s.split("\n----\n")

答案 3 :(得分:0)

更少的代码使其完美如预期:

在:

re.split('[\n-]+', s, re.MULTILINE)

OUT:

['width:5', 'This is a test sentence to test the width thing']

答案 4 :(得分:0)

你有没有尝试过:

result = re.split("^----$", subject_text, 0, re.MULTILINE)