透過正規表示式僅匹配最內部的環境

透過正規表示式僅匹配最內部的環境

我想匹配 的最內部環境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

相關內容