正则表达式匹配液体代码 [英] Regular expression matching liquid code

查看:242
本文介绍了正则表达式匹配液体代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jekyll建立一个网站,我想从给定的HTML文件中自动删除液体代码(和 液体代码)。我在Python中使用正则表达式来做这件事,到目前为止我有这样一个:
$ b

I'm building a website using Jekyll I would like to automatically remove liquid code (and only liquid code) from a given HTML file. I'm doing it in Python using regular expressions, and so far I have this one:

\{.*?\}|\{\{.*?\}\}

由于我对液体(和.html)不太熟悉,有人可以证实这足以实现我的目标吗?

As I am not too familiar with liquid (and .html), could someone confirm that this will suffice for my goal?

以下是类型的文件我将与之合作:
$ b

Here is an example of the kind of file I will be working with:

<div class="post-preview">
    <div class="post-title">
        <div class="post-name">
            <a href="{{ post.url }}">{{ post.title }}</a>
        </div>
        <div class="post-date">
            {% include time.html %}
        </div>
    </div>

    <div class="post-snippet">
        {% if post.content contains '<!--break-->' %}
            {{ post.content | split:'<!--break-->' | first }}
            <div class="post-readmore">
                <a href="{{ post.url }}">read more-></a>
            </div>
        {% endif %}
    </div>
    {% include post-meta.html %}
</div>

在这种情况下,我的正则表达式可行,但我想确保我不会错过未来。我可以采用一种诡异的方式,用所有的注释来包围所有的液体代码,比如 $ b

In this case my regex works, but I wanted to make sure I'm not missing something for the future. I could go for a hackish way and surround all liquid code with comments like

/* start_liquid */ {blalala} /* end_liquid */

但我正在寻找更优雅的方式

but I'm looking for a more elegant way to do it.

推荐答案

不是,只有你可以使用脏解决方案,例如:

I am not saying that you should but you could use a "dirty" solution like:

{%\ (if)[\s\S]*?{%\ end\1\ %}|
{%.+?%}|
{{.+?}}

这与所有提供的模板代码匹配, regex101.com上的演示

额外的调整是扩展交替组(,如果)或完全使用解析器。

This matches all of the template code provided, see a demo on regex101.com.
Additional tweaks would be to extend the alternation group (if) or use a parser altogether.

这篇关于正则表达式匹配液体代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆