通过正则表达式仅匹配最内部的环境

通过正则表达式仅匹配最内部的环境

我想匹配 的最内部环境begin{question}及其对应的end{question}.

示例数据

\section{Takayasu arteritis}

\begin{question}
{You get a patient. 
What do you notice first in this patient?}
Absence of peripheral pulse.
\end{question}

\begin{question}
{What was the first Takayasu case?}
Young woman in Asia with red vessels in the eye. 
So special eye diagnosis done. 
Affects eye.
\end{question}


Fever of unknown origin can be used when you do not know what is causing the disease. 

% Show cases in MedScape and ask class. 

Aneurysms. 


\subsection{Treatment}

\begin{question}
{What you should always include in Takayasu treatment? 
What are the symptoms?}
Blood pressure.
Aneurysms which will burst without treatment. 
So blood pressure decreasing drugs like beta blockers along in combination with other drugs.
\end{question}

我的预期输出是

\begin{question}
{You get a patient. 
What do you notice first in this patient?}
Absence of peripheral pulse.
\end{question}

或者

\begin{question}
{What was the first Takayasu case?}
Young woman in Asia with red vessels in the eye. 
So special eye diagnosis done. 
Affects eye.
\end{question}

或者

\begin{question}
{What you should always include in Takayasu treatment? 
What are the symptoms?}
Blood pressure.
Aneurysms which will burst without treatment. 
So blood pressure decreasing drugs like beta blockers along in combination with other drugs.
\end{question}

怎么能只匹配最内部的环境呢?

答案1

尝试这个:

pcregrep -M '\\begin{question}(.|\n)*?\\end{question}'

解释:

  • pcregrep: grep 与 Perl 兼容的正则表达式
  • -M:允许模式匹配多行
  • (.|\n)*?:在非贪婪模式下,任何普通字符.或换行符\n匹配零次或多次。.?

结果:

\begin{question}
{You get a patient. 
What do you notice first in this patient?}
Absence of peripheral pulse.
\end{question}
\begin{question}
{What was the first Takayasu case?}
Young woman in Asia with red vessels in the eye. 
So special eye diagnosis done. 
Affects eye.
\end{question}
\begin{question}
{What you should always include in Takayasu treatment? 
What are the symptoms?}
Blood pressure.
Aneurysms which will burst without treatment. 
So blood pressure decreasing drugs like beta blockers along in combination with other drugs.
\end{question}

答案2

您需要它成为一个纯粹的正则表达式解决方案,还是只是消失?

perl -lne 'print if(/^\\begin{question}/ .. /^\\end{question}/)'  file

相关内容