Python Regex:匹配任何不包括2个单词的文本(可能环顾四周)

发布于 2025-02-09 14:59:37 字数 832 浏览 0 评论 0原文

我正在尝试制作与这样匹配标签的正则(这样我可以用空白代替它们):

{# This is a comment #}
{% if cows > pandas %}
{{ my_variable }}

但是,如果标签中的第一个单词是扩展了,则不得匹配标签(它将始终与{%%}令牌配对。

例如,

{% include 'foo.html' %}
{% extends 'foo/bar/baz.html' %}

我有以下Python Regex,

{[{#%]\s*.*?(?!include|extends)[}#%]}

但是负面断言不起作用(例如,以下匹配和排除在下面):

{# match this #}
{% match this %}
{{ match this }}
asdf
{% foo 'match this' %} asdf {% foo 'match this' %} asdf
{% include 'not this' %}
{% extends 'not this' %}
asdf

注意:是的,如果您有兴趣,这与django templating有关!

I am trying to make a regex that matches tags like this (so I can substitute them with blanks):

{# This is a comment #}
{% if cows > pandas %}
{{ my_variable }}

However if the first word in the tags is includes or extends then it must not match the tag (it will always be paired with {% %} tokens fyi).

e.g.

{% include 'foo.html' %}
{% extends 'foo/bar/baz.html' %}

I have the following python regex

{[{#%]\s*.*?(?!include|extends)[}#%]}

However the negative assertion is not working (i.e include and exclude are matched below):

{# match this #}
{% match this %}
{{ match this }}
asdf
{% foo 'match this' %} asdf {% foo 'match this' %} asdf
{% include 'not this' %}
{% extends 'not this' %}
asdf

Note: Yes this is to do with Django templating if you are interested!

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

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

发布评论

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

评论(1

孤凫 2025-02-16 14:59:38

您可以使用

{[{#%](?!\s*(?:include|extends)\b).*?[}#%]}

regex demo

详细信息

  • { - a { char
  • [{#%] - a { char
  • (?!\ s*(?inclage |扩展)如果有零或以上的空格,则include单词作为当前位置的右侧单词延伸为
  • 。*?? -零或更多字符以外的其他字符除line Break chars以外的
  • > [}#%] - a }%< /code> char
  • } - a } char。

You can use

{[{#%](?!\s*(?:include|extends)\b).*?[}#%]}

See the regex demo.

Details:

  • { - a { char
  • [{#%] - a {, # or % char
  • (?!\s*(?:include|extends)\b) - a negative lookahead that fails the match if there are zero or more whitespaces followed with include or extends words as whole words immediately to the right of the current location
  • .*? - any zero or more chars other than line break chars as few as possible
  • [}#%] - a }, # or % char
  • } - a } char.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文