如果找到特定字符串,Regex将停止匹配


Regex stop matching if a specific string is found

我有以下正则表达式:

/{%'h?if ((?:@)?(?:[a-zA-Z_'x7f-'xff][a-zA-Z0-9_'x7f-'xff]*)(?:'.(?:[a-zA-Z0-9_'x7f-'xff][a-zA-Z0-9_'x7f-'xff]*))*)'h?%}(['s'S]*){%'h?end if'h?%}/U

它基本上匹配以下内容:

{% if variable %}
whatever stuff
{% end if %}

我正试图修改它以匹配上面或下面的内容:

{% if variable %}
some stuff
{% else %}
whatever stuff
{% end if %}

之后我想说if else_capture_group is not empty, then do something

我试着看负面广告:

{%'h?if ((?:@)?(?:[a-zA-Z_'x7f-'xff][a-zA-Z0-9_'x7f-'xff]*)(?:'.(?:[a-zA-Z0-9_'x7f-'xff][a-zA-Z0-9_'x7f-'xff]*))*)'h?%}(['s'S](?!{% else %}))(?:{%'h?else'h?%}(['s'S]*))?{%'h?end if'h?%}

但根据:https://regex101.com/r/wP4vS9/1,它不起作用。。。我不知道为什么。有人能给我指正确的方向吗?

在这里,我试图缩短它,并添加了一个经过回火的贪婪令牌,使它与可选的else块一起工作:

(?s){%'s*if's+(?<var>@?(?:[a-zA-Z_'x7f-'xff][a-zA-Z0-9_'x7f-'xff]*)(?:'.(?:(?1)))*)'h*%}(?<if>(?:(?!{% e(?:lse|nd if) %}).)*)(?:{%'h*else'h*%}(?<else>['s'S]*?))?{%'h*end if'h*%}

查看regex演示

一些细节:

  • {%'s*if's+(?<var>@?(?:[a-zA-Z_'x7f-'xff][a-zA-Z0-9_'x7f-'xff]*)(?:'.(?:(?1)))*)'h*%}-我们捕获var部分的第一部分(捕获组可能需要调整,但想法很清楚)
  • (?<if>(?:(?!{% e(?:lse|nd if) %}).)*)-用于匹配和捕获if代码块的钢化贪婪令牌
  • (?:{%'h*else'h*%}(?<else>['s'S]*?))?-与else部分匹配的可选组(由于末尾为?
  • {%'h*end if'h*%}-end分隔符