2016-10-01 147 views
0

我有一个Perl脚本,它看起来举例如下醒目定界符:正则表达式在JavaScript

#/usr/bin/perl -w 

print 'My output: '; 

print <<END; 
Here is more content 
which is printed with 
heredoc style 
END 

print 'End of output'; 

现在我希望提取使用JavaScript上述定界符打印的内容。结果应该如下所示:

<<END; 
Here is more content 
which is printed with 
heredoc style 
END 

我试过了<<END(.|\n)*END。如果文档只包含一个heredoc,但如果它包含多个heredoc则不起作用。

因此,举例来说,如果我的Perl脚本如下所示:

#/usr/bin/perl -w 

print 'My output: '; 

print <<END; 
Here is more content 
which is printed with 
heredoc style 
END 

print <<END; 
Here is even more content 
which is printed with 
heredoc style 
END 

print 'End of output'; 

正则表达式匹配:

<<END; 
Here is more content 
which is printed with 
heredoc style 
END 

print <<END; 
Here is even more content 
which is printed with 
heredoc style 
END 

但它应该匹配

<<END; 
Here is more content 
which is printed with 
heredoc style 
END 

<<END; 
Here is even more content 
which is printed with 
heredoc style 
END 

有没有人有一个想法,我的正则表达式有什么问题?

另一个问题:它是否可能与正则表达式,以捕获所有heredocs它没有指定到heredoc字符串END

回答

2

问题是*默认为“贪婪”。 *捕获它可以匹配的所有项,直到*之前的模式失败。只有这样才会回来。在你的情况下,该模式一直有效直到字符串的末尾。

为了防止它被贪婪,并检查它是否通过了应该结束的点(请参阅我在那里做了什么?:D),在*后面加上?

<<END(.|\n)*?END 
+0

不错的解决方案。你认为可以在不指定heredoc字符串'END'的情况下捕获heredoc字符串吗? –

+0

@BenjaminJ。寻找“反向引用”。 – Joseph

+0

非常感谢。我的解决方案是<<((。)*); \ n(。| \ n)*?\ 1' –