如何使用python打印正则表达式搜索后的下一行

2024-10-03 15:26:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下文字:

subject = "Madam / Dear Sir, ', ' ', 'The terrorist destroyed the building at 23:45 with a remote 
            detonation device', ' ', 'so a new line character is appended to the string"

我已使用以下正则表达式代码进行搜索:

[p for p in re.split('\,', str(subject)) if re.search('(M[a-z]+ / \w+ \w+r)', p)]

获取输出:女士/亲爱的先生

预期输出:恐怖分子在23:45用遥控器摧毁了大楼 起爆装置

请注意,预期输出应始终在找到正则表达式之后

你能帮我一下吗


Tags: thereremotewithmadamatsubject文字
1条回答
网友
1楼 · 发布于 2024-10-03 15:26:17

您可以进一步扩展分割\s*',\s*'\s*,以匹配所有不需要的部分,直到下一个需要的部分

然后使用循环首先匹配模式M[a-z]+ / \w+ \w+r。如果存在项目,则获取下一个项目

示例代码

import re
subject = "Madam / Dear Sir, ', ' ', 'The terrorist destroyed the building at 23:45 with a remote detonation device', ' ', 'so a new line character is appended to the string"
filteredList = list(filter(None, re.split("\s*',\s*'\s*", subject)))
l = len(filteredList)
for i, s in enumerate(filteredList):
    if re.match(r"M[a-z]+ / \w+ \w+r", s) and i + 1 < l:
        print(filteredList[i + 1])

输出

The terrorist destroyed the building at 23:45 with a remote detonation device

Python demo

相关问题 更多 >