如何使用re2正则表达式否定字符串模式? [英] How to negate string pattern using re2 regex?

查看:309
本文介绍了如何使用re2正则表达式否定字符串模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google re2 正则表达式来查询 Prometheus 在Grafana仪表板上.尝试通过以下3种可能的输入字符串从键中获取价值

I'm using google re2 regex for the purpose of querying Prometheus on Grafana dashboard. Trying to get value from key by below 3 types of possible input strings

 1. object{one="ab-vwxc",two="value1",key="abcd-eest-ed-xyz-bnn",four="obsoleteValues"}
 2. object{one="ab-vwxc",two="value1",key="abcd-eest-xyz-bnn",four="obsoleteValues"}
 3. object{one="ab-vwxc",two="value1",key="abcd-eest-xyz-bnn-ed",four="obsoleteValues"}

..具有以下所列的验证

..with validation as listed below

  • 应包含abcd-
  • 不应包含-ed
  • should contain abcd-
  • shouldn't contain -ed

以某种方式此正则表达式

\bkey="(abcd(?:-\w+)*[^-][^e][^d]\w)"

..满足第一个条件abcd-,但不满足第二个条件(取反-ed).

..satisfies the first condition abcd- but couldn't satisfy the second condition (negating -ed).

第二个输入选项的预期输出为abcd-eest-xyz-bnn.任何帮助将非常感激.非常感谢.

The expected output would be abcd-eest-xyz-bnn from the 2nd input option. Any help would be really appreciated. Thanks a lot.

推荐答案

如果我正确理解了您的要求,则以下模式应该有效:

If I understand your requirements correctly, the following pattern should work:

\bkey="(abcd(?:-e|-(?:[^e\W]|e[^d\W])\w*)*)"

演示 .

Demo.

重要部分的故障:

(?:                 # Start a non-capturing group.
    -e              # Match '-e' literally.
    |               # Or the following...
    -               # Match '-' literally.
    (?:             # Start a second non-capturing group.
        [^e\W]      # Match any word character except 'e'.
        |           # Or...
        e[^d\W]     # Match 'e' followed by any word character except 'd'.
    )               # Close non-capturing group.
    \w*             # Match zero or more additional word characters.
)                   # Close non-capturing group.

或者简单地说:

匹配连字符,然后:

Match a hyphen followed by:

  • 仅字母"e". 或..
  • 不是开头的单词 * . 或..
  • 以'e'开头的单词,后面没有'd'.
  • only the letter 'e'. Or..
  • a word* not starting with 'e'. Or..
  • a word starting with 'e' not followed by 'd'.


* 一个单词"这里是指正则表达式中定义的一串字字符.

这篇关于如何使用re2正则表达式否定字符串模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆