regex Perl使用跨越多行的递归来匹配文本

g6baxovj  于 12个月前  发布在  Perl
关注(0)|答案(1)|浏览(165)

在下面的文本中,我试图匹配\rem{lp}{some text with nested curly braces}regex101.com example适用于正则表达式:

([^\s]*\s*)\\rem\{(?:lp|db)\}(\{((?>[^{}]|\n|(?2))*)\})(\s?[^\s]*)

字符串
我也希望它能在Perl中工作:

/([^\s]*\s*)\\rem\{(?:lp|db)\}(\{((?>[^{}]|\n|(?2))*)\})(\s?[^\s]*)/g


然而,perl版本失败了(文件text.txt包含下面的文本)。这似乎是由于换行符。我如何纠正这一点(我也试图添加m修饰符没有帮助?

perl -ne 'while(/([^\s]*\s*)\\rem\{(?:lp|db)\}(\{((?>[^{}]|\n|(?2))*)\})(\s?[^\s]*)/g){print ++$a."$&\n";}' test.txt


test.txt

Some text etc word\rem{lp}{ more text {\ce{O2}} further text {\ce{H2O}} . some other text the $m = 48$ ({\ce{O2}}) ps}.

\rem{lp}{ more text {\ce{O2}} further text {\ce{H2O}} . some other text the $m = 48$ ({\ce{O2}}) ps 
where  more text {\ce{O2}} further text {\ce{H2O}} . some other text the $m = 48$ ({\ce{O2}}) ps from 
who  more text {\ce{O2}} further text {\ce{H2O}} . some other text the $m = 48$ ({\ce{O2}}) ps.}

\rem{lp}{ more text {\ce{O2}} further text {\ce{H2O}} . some other text the $m = 48$ ({\ce{O2}}) ps. 
 more text {\ce{O2}} further text {\ce{H2O}} . some other text the $m = 48$ ({\ce{O2}}) ps.}

\subsection{other}
Our bla bla bla

vecaoik1

vecaoik11#

以防有人偶然发现这个问题。Perl不会在一行中发出声音,所以while部分仍然逐行读取。

perl -0777 -ne 'while(/([^\s]*\s*)\\rem\{(?:lp|db)\}(\{((?>[^{}]|\n|(?2))*)\})(\s?[^\s]*)/g){print ++$a."$&\n";}' test.txt

字符串

相关问题