擅长:python、mysql、java
<p>要匹配关键字前后的两行,请使用如下正则表达式:</p>
<pre><code>(?:.*(?:\r?\n)+){2}age(?:.*(?:\r?\n|$)+){3}
</code></pre>
<p><a href="https://regex101.com/r/8OMPAr/1" rel="nofollow noreferrer"><strong>Demo</strong></a></p>
<p>说明:</p>
<ul>
<li><code>(?:.*(?:\r?\n|$)+){3}</code>实际上,您需要匹配其中的3个块,因为第一个换行符直接位于关键字(<code>age</code>)之后,下一个换行符位于第4行(<code>25</code>)的末尾。因此,需要第三次重复。你知道吗</li>
</ul>
<p>但是,由于这可能是字符串的结尾,我添加了<code>$</code>作为替代。我还在<code>\r</code>之前添加了一个可选的<code>\n</code>,如果字符串可能包含Windows行结束符,则可以使用它,否则就删除它们。你知道吗</p>
<p><a href="https://ideone.com/8iILGX" rel="nofollow noreferrer">Sample code</a>:</p>
<pre><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())
</code></pre>