首页 > 解决方案 > 在正则表达式中选择标题行下方的一组行

问题描述

这是我的问题。我正在为电影类型脚本(不是计算机脚本,而是剧本)创建解析器,我需要选择某个场景标题下的所有行。这是莎士比亚的《哈姆雷特》中的示例脚本。

#Scene 1#
Bernardo: Who's there?
Francisco: Nay, answer me: stand, and unfold yourself.

#Scene 2#
Horatio: Tis now struck twelve; get thee to bed, Francisco.
Marcellus: Peace, break thee off; look, where it comes again!

我需要一种方法来选择“#Scene 1#”和“#Scene 2#”之间的所有内容。Bernardo 和 Francisco 应该匹配,但 Horatio 和 Marcellus 不应该匹配。

我尝试过使用前瞻和后瞻,但显然它们不能跨多行工作。

/(?<=#Scene 1#)(.*)(?=#Scene 2#)/gim

如果它很重要,我使用的是 Python 2.7。

标签: pythonregex

解决方案


这个正则表达式的解释在这里

import re

data = """
#Scene 1#
Bernardo: Who's there?
Francisco: Nay, answer me: stand, and unfold yourself.

#Scene 2#
Horatio: Tis now struck twelve; get thee to bed, Francisco.
Marcellus: Peace, break thee off; look, where it comes again!
"""

print(re.findall(r'(?:#Scene 1#)\s*(.*?)\s*(?:#Scene 2#)', data, flags=re.DOTALL)[0])

印刷:

Bernardo: Who's there?
Francisco: Nay, answer me: stand, and unfold yourself.

推荐阅读