【问题标题】:Regex stop matching if a specific string is found如果找到特定字符串,则正则表达式停止匹配
【发布时间】:2016-04-15 21:06:43
【问题描述】:

我有以下正则表达式:

/{%\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,它不起作用......我不知道为什么。有人能指出我正确的方向吗?

【问题讨论】:

    标签: php regex templates


    【解决方案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 demo

    一些细节:

    • {%\s*if\s+(?&lt;var&gt;@?(?:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(?:\.(?:(?1)))*)\h*%} - 我们捕获var 部分的第一部分(捕获组可能需要调整,但思路很明确)
    • (?&lt;if&gt;(?:(?!{% e(?:lse|nd if) %}).)*) - 一个缓和的贪婪令牌,用于匹配和捕获 if 代码块
    • (?:{%\h*else\h*%}(?&lt;else&gt;[\s\S]*?))? - 与else 部分匹配的可选组(由于末尾为?
    • {%\h*end if\h*%} - end 分隔符

    【讨论】:

    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    相关资源
    最近更新 更多