使用跨多行的递归进行 Perl 匹配文本

Perl matching text using recursions spanning multiple lines

提问人:atapaka 提问时间:10/26/2023 最后编辑:Barmaratapaka 更新时间:10/26/2023 访问量:42

问:

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

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

我希望它也能在perl中工作:

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

但是,perl 版本失败(该文件包含以下文本)。这似乎是由于换行符造成的。我该如何纠正这个问题(我也尝试在没有帮助的情况下添加修饰符?text.txtm

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
正则表达式 Perl 正则表达式递归

评论

0赞 Barmar 10/26/2023
确保文件有换行符,而不是 .如有必要,用于修复它。LFCRLFdos2unix
0赞 Barmar 10/26/2023
或者更改正则表达式以代替 .\r?\n\n
0赞 atapaka 10/26/2023
@Barmar这无济于事。另请注意,regex101 版本在没有的情况下运行良好,我认为不需要它,因为它包含在集合中,这只是我绝望的尝试之一。\n[^{}]
0赞 Cary Swoveland 10/26/2023
在您的示例中,我将其视为两个级别的嵌套大括号(例如,)。是总是这样,还是嵌套级别可能更小或更大?{some text with nested curly braces}\rem{lp}{some text with nested curly braces}{\ce{O2}}

答:

1赞 atapaka 10/26/2023 #1

以防万一有人偶然发现这一点。Perl 不会在一行中啜饮,因此该部分是逐行读取的。为了解决这个问题,人们必须运行while

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