使用正则表达式匹配 HTML 中的一对注释

发布于 2024-07-17 08:47:56 字数 489 浏览 5 评论 0原文

我有一个看起来像这样的 mako 模板:

% if staff:
    <!-- begin staff -->
    ...
    <!-- end staff -->
% endif

这样,如果我将 Staff 变量传递为 True,那么这些注释应该会出现。 我尝试使用如下所示的正则表达式来测试这一点:

re.search('<!-- begin staff -->.*<!-- end staff -->', text)

我已验证注释是否出现在 HTML 输出中,但正则表达式不匹配。 我什至尝试将注释 () 通过 re.逃脱,但仍然没有运气。 我究竟做错了什么?

或者有更好的方法来运行这个测试吗?

I have a mako template that looks something like this:

% if staff:
    <!-- begin staff -->
    ...
    <!-- end staff -->
% endif

That way if I pass the staff variable as being True, those comments should appear. I'm trying to test this by using a regular expression that looks like this:

re.search('<!-- begin staff -->.*<!-- end staff -->', text)

I've verified that the comments appear in the HTML output, but the regular expression doesn't match. I've even tried putting the comments (<!-- begin staff --> and <!-- end staff -->) through re.escape, but still no luck. What am I doing wrong?

Or is there a better way to run this test?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

年华零落成诗 2024-07-24 08:47:56

默认情况下 . 不匹配换行符 - 您需要添加 re.DOTALL 选项。

re.search('<!-- begin staff -->.*<!-- end staff -->', text, re.DOTALL)

如果您有多个员工部分,您可能还希望使匹配变得非贪婪:

re.search('<!-- begin staff -->.*?<!-- end staff -->', text, re.DOTALL)

By default . doesn't match newlines - you need to add the re.DOTALL option.

re.search('<!-- begin staff -->.*<!-- end staff -->', text, re.DOTALL)

If you have more than one staff section, you might also want to make the match ungreedy:

re.search('<!-- begin staff -->.*?<!-- end staff -->', text, re.DOTALL)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文