问题
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