python - 使用正则表达式从字符串中提取文本

标签 python regex

我有一个非常大的字符串。该字符串中有很多段落。每个段落都以标题开头,并遵循特定模式。

例子:

== Title1 ==//段落开始 ........................ ............//一些文本 ........................ 段落结束 ===Title2 ===//段落开始 ........................ ............//一些文本 ........................

标题的格式是:

1.) New Paragraph title starts with an equal to ( = ) and can be followed by any number of =.

2.) After = , there can be a white space ( not necessary though ) and it is followed by text.

3.) After text completion, again there can be a white space ( not necessary ), followed by again any number of equal to's ( = ).

4.) Now the paragraph starts. I have to extract the text until it encounters a similar pattern.

任何人都可以帮助我如何使用正则表达式执行此操作吗?时间差

最佳答案

你可以使用

re.findall(r'(?m)^=+[^\S\r\n]*(.*?)[^\S\r\n]*=+\s*(.*(?:\r?\n(?!=+.*?=).*)*)', s)

参见 regex demo

详情

  • (?m)^ - 一行的开始
  • =+ - 1 个或多个 = 字符
  • [^\S\r\n]* - 除 CR 和 LF 之外的零个或多个空白字符
  • (.*?) - 第 1 组:任何零个或多个字符,换行字符除外,尽可能少
  • [^\S\r\n]* - 除 CR 和 LF 之外的零个或多个空白字符
  • =+ - 1 个或多个 = 字符
  • \s* - 0+ 个空格
  • (.*(?:\r?\n(?!==+.*?=).*)*) - 第 2 组:
    • .* - 任何零个或多个字符,除换行字符外,尽可能多
    • (?:\r?\n(?!=+.*?=).*)* - 零个或多个序列
      • \r?\n(?!=+.*?=) - 一个可选的 CR,然后是 LF,后面没有跟 1+ =,然后除换行符以外的任何字符尽可能少,然后再 1+ =s
      • .* - 任何零个或多个字符,除换行字符外,尽可能多

Python demo :

import re

rx = r"(?m)^=+[^\S\r\n]*(.*?)[^\S\r\n]*=+\s*(.*(?:\r?\n(?!=+.*?=).*)*)"
s = "== Title1 ==\n..........................\n.............\nEnd of Paragraph\n===Title2 ===\n.............\n.............\n............."
print(re.findall(rx, s))

输出:

[('Title1', '..........................\n.............\nEnd of Paragraph'), ('Title2', '.............\n.............\n.............')]

关于python - 使用正则表达式从字符串中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51893787/

相关文章:

regex - 用于货币的 Linux sed 正则表达式

python - 如何匹配 *仅* 六位数版本?

python - 处理正则表达式中的空格

python - 使用 python dblquad 进行复平面中的区域积分

python - 访问lru_cache的缓存

python - 让 Omni 完整地在 Windows 上的 vim 7.2 上工作

用于表单验证的正则表达式 1-9999

python - 测试 nameko 基本示例时出现 BlockingIOError

python - 如何拆分和连接 Pandas 数据框

javascript - 用于删除导致关键字的字符串的第一部分的正则表达式