正規表現で最も内側の環境のみにマッチさせる

正規表現で最も内側の環境のみにマッチさせる

の最も内側の環境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: Perl互換の正規表現によるgrep
  • -M: パターンが複数の行に一致することを許可する
  • (.|\n)*?:非貪欲モードで、任意の通常の文字.または改行\nが 0 回以上一致します。.?

結果:

\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 風にする必要がありますか?

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

関連情報