【问题标题】:regex for catching heredoc in JavaScript用于在 JavaScript 中捕获 heredoc 的正则表达式
【发布时间】:2017-02-10 04:00:02
【问题描述】:

我有一个 perl 脚本,例如如下所示:

#/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 提取上述 heredoc 打印的内容。结果应如下所示:

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

我已经用&lt;&lt;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

有人知道我的正则表达式有什么问题吗?

另一个问题:是否可以仅使用正则表达式来捕获所有未指定到 heredoc 字符串 END 的 heredocs?

【问题讨论】:

    标签: javascript regex heredoc


    【解决方案1】:

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

    为了防止它变得贪婪并检查它是否通过了应该结束的点(看看我在那里做了什么?:D),在* 之后添加?

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

    【讨论】:

    • 不错的解决方案。你认为可以在不指定heredoc字符串END的情况下捕获heredoc字符串吗?
    • @BenjaminJ。寻找“反向引用”。
    • 非常感谢。我的解决方案是&lt;&lt;((.)*);\n(.|\n)*?\1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 2022-07-29
    • 2019-01-27
    • 2016-02-10
    • 2013-10-31
    • 2021-08-26
    相关资源
    最近更新 更多