Python:如何在一次搜索中找到 \r\n\r\n

1 投票
2 回答
3281 浏览
提问于 2025-04-16 00:38

我需要根据第一次出现的 \r\n\r\n 来分割文件内容。

我希望有灵活性,也就是说,行可以以 \r\n\r\n\n\n 结束。

怎么才能分割这些文本呢?

这里有个例子:

\===================FILE BEGIN==========================================
name: about

title: About

publish: True

order: -1

\r\n

\r\n


**example.com** is a example website provides the latest examples in organized way. 

Blah blah blah....
Blah blah blah....
Blah blah blah....
\===================File END==========================================

第一部分是我的头部信息(用yaml格式),用于文件的标识,第二部分是markdown文本。

2 个回答

0

这个正则表达式模式 "\r\n\r\n|\n\n" 应该是有效的。你只需要使用 re.split 或者 Regex.split,并把 maxsplit=1 设置上就可以了。

2
import re

linend = re.compile(r'\r\n\r\n|\n\n')
s = 'an example\n\nstring\n\nhere'
print linend.split(s, 1)
s = 'another\r\n\r\nexample\r\n\r\nhere'
print linend.split(s, 1)

打印输出:

['an example', 'string\n\nhere']
['another', 'example\r\n\r\nhere']

如你所要求的。

撰写回答