Regex for matching a tag in a Liquid template : “>” inside html tag

寵の児 提交于 2021-02-10 06:49:07

问题


I have to write a match pattern for the body tag in a Liquid template.

While matching HTML tags is pretty straightforward, I have the problem that HTML special character can be used inside the Liquid code. Example:

<body class="template-{{ template | replace: '.', ' ' | truncatewords: 
1, '' }}{% if promo %}has-promo{% endif %} {% if products.size > 1 
%}has-related-products{% endif %} {% if settings.product-hover == 
'quick-shop' %}has-quick-shop{% endif %} loading" >

or simplified:

<body {% bla > 1 %} bla bla>

My current match pattern /<body(.[^>]*)>/s matches the above code until the first >. I need a pattern that matches the whole tag.


回答1:


Try with:

/<body(.[^>{}]*(?:{+[^}]*}+[^>{}]*)*)>/s

See demo

Instead of [^>]* the regex uses [^>{}]*(?:{+[^}]*}+[^>{}]*)*, that matches any character but >, { or }; at some point it can meet a {, so it matches the whole content of {+something}+, followed again by [^>{}]*. This trick is repeated many times with the last *.



来源:https://stackoverflow.com/questions/43778063/regex-for-matching-a-tag-in-a-liquid-template-inside-html-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!