为compile runtime关键字编写正则表达式

2024-10-04 01:37:28 发布

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

text = """ Pratap
pandey
age
25
student
"""
keyword = "age"

re_compile = re.compile('((.*\n+){2})keyword((.*\n+){2})')
re_result = re.findall(re_compile, text)

我想写一个正则表达式来提取关键字前两行和关键字后两行关键字匹配时,与变量。你知道吗


Tags: textreage关键字resultkeywordstudentcompile
3条回答

要匹配关键字前后的两行,请使用如下正则表达式:

(?:.*(?:\r?\n)+){2}age(?:.*(?:\r?\n|$)+){3}

Demo

说明:

  • (?:.*(?:\r?\n|$)+){3}实际上,您需要匹配其中的3个块,因为第一个换行符直接位于关键字(age)之后,下一个换行符位于第4行(25)的末尾。因此,需要第三次重复。你知道吗

但是,由于这可能是字符串的结尾,我添加了$作为替代。我还在\r之前添加了一个可选的\n,如果字符串可能包含Windows行结束符,则可以使用它,否则就删除它们。你知道吗

Sample code

import re
regex = r"(?:.*(?:\r?\n)+){2}age(?:.*(?:\r?\n|$)+){3}"
test_str = (" Pratap\n"
    "pandey\n"
    "age\n"
    "25\n"
    "student")

matches = re.finditer(regex, test_str, re.MULTILINE)
for match in matches:
    matchNum = matchNum + 1    
    print (match.group())

Python 2.7中可能的解决方案

您可以使用未编译的正则表达式,并在其中放入一些字符串格式。你知道吗

from __future__ import print_function

import re

text = """ Pratap
pandey
age
25
student
"""
keywords = ("age", "else")

for key in keywords :
    print(re.findall(r'(.*\n+)(.*\n+){}\n+(.*\n+)(.*\n+)'.format(key), text))

输出:

[(' Pratap\n', 'pandey\n', '25\n', 'student\n')]
[]

(*)编辑的正则表达式。

我不太清楚你在问什么。我想你想问的是如何输入一个名为“keyword”的变量的值

你就是这样做的

re.compile(f"(((.*\n+){{2}})\\s*{keyword}\\s*\n((.*\n+){{2}}))")

如果您定义keyword=<;some value>;,则上面的代码将起作用。你知道吗

顺便说一句,你需要使用组1时提取得到你想要的。你知道吗

相关问题 更多 >