正则表达式:匹配除完整标记之外的任何内容

发布于 2024-07-10 13:28:58 字数 493 浏览 3 评论 0原文

我有以下代码片段,我想使用正则表达式提取 {foreach}{/foreach} 之间的代码:

{foreach (...)}
Some random HTML content <div class="">aklakdls</div> and some {$/r/template} markup inside.
{/foreach}

我已经有:

{foreach [^}]*}

但我无法之后匹配任何内容。 有什么方法可以匹配除 {/foreach} 之外的任何内容作为整个标记吗? 请注意,{foreach}{/foreach} 之间的内容还可以包含“{$”标记。

编辑:BaileyP's & Tomalak 的答案是正确的,但为了简单起见,我选择了 BaileyP 的答案。

I have the following snippet where I would like to extract code between the {foreach} and {/foreach} using a regular expression:

{foreach (...)}
Some random HTML content <div class="">aklakdls</div> and some {$/r/template} markup inside.
{/foreach}

I already have:

{foreach [^}]*}

but I am unable to match anything after that. Is there any way to match anything BUT {/foreach} as a whole token? Please note that the content between {foreach}{/foreach} can also contain "{$" tokens.

Edit: BaileyP's & Tomalak's answers are correct, but I have chosen BaileyP's answer for simplicity sake.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

潇烟暮雨 2024-07-17 13:28:58

我想出了这个

/(?:{foreach .*?})(.*?)(?:{\/foreach})/gis

测试 RegExr

I came up with this

/(?:{foreach .*?})(.*?)(?:{\/foreach})/gis

Tested with RegExr

怪我鬧 2024-07-17 13:28:58

如果您的正则表达式风格不支持非贪婪匹配,则以下内容可以做到这一点,但由于它确实如此,我建议 @BaileyP 的回答

\{foreach [^}]*\}((?:.(?!\{/foreach\}))*[^{]?)

根据您对正则表达式的偏好,负零宽度前瞻和非捕获组看起来有点不同。

以下是组件:

\{foreach [^}]*\}  // pretty much self-explanatory
(                  // match group one starts (that's what you are looking for)
 (?:               // non-capturing group starts
  .                // anything...
  (?!\{/foreach\}) // ... that is not followed by "{/foreach}"
 )*                // non-capturing group ends, repeat as often as possible
 [^{]?             // match the last character, unless it is "{"
)                  // match group one ends, done

If your regex flavor did not support non-greedy matching, the following would do it, but since it does I recommend @BaileyP's answer.

\{foreach [^}]*\}((?:.(?!\{/foreach\}))*[^{]?)

Depending on your regex favour, negative zero-width look-ahead and non-capturing groups look a little different.

Here are the components:

\{foreach [^}]*\}  // pretty much self-explanatory
(                  // match group one starts (that's what you are looking for)
 (?:               // non-capturing group starts
  .                // anything...
  (?!\{/foreach\}) // ... that is not followed by "{/foreach}"
 )*                // non-capturing group ends, repeat as often as possible
 [^{]?             // match the last character, unless it is "{"
)                  // match group one ends, done
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文