python - 在正则表达式中选择标题行下方的一组行
问题描述
这是我的问题。我正在为电影类型脚本(不是计算机脚本,而是剧本)创建解析器,我需要选择某个场景标题下的所有行。这是莎士比亚的《哈姆雷特》中的示例脚本。
#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。
解决方案
这个正则表达式的解释在这里。
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.
推荐阅读
- css - How to shrink the width of div when the elements are removed in resize div
- javascript - PDF file not opening in new tab SAP UI5 for Arabic language document in chrome
- java - How to run .jar in Android and see the results in Android
- slack - 您如何跟踪 Slack 应用程序的分析
- php - 使用 Typo3 9.5 LTS 站点配置定义“插件”类型的自定义 RouteEnhancer 时,如何实现可选的空参数?
- c++ - 唯一指针:左值引用与右值引用函数调用
- javascript - 精灵上方的精灵或画布作为 HTML 背景
- python - Keras 在没有 TensorFlow 的情况下从 CSV 创建数据集
- java - 如果还有 java 8 Lambda
- javascript - Angular Electron - 打印到 PDF 可用于开发,但不能用于生产