如何使用 re2 正则表达式否定字符串模式?

2024-05-26

我正在使用谷歌re2 https://github.com/google/re2/wiki/Syntax用于查询目的的正则表达式普罗米修斯 https://prometheus.io/docs/prometheus/latest/querying/examples/#simple-time-series-selection在 Grafana 仪表板上。尝试通过以下 3 种可能的输入字符串从 key 获取值

 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"}

..经过下面列出的验证

  • 应包含abcd-
  • 不应该包含-ed

Somehow 这个正则表达式 https://regex101.com/r/I5Wsbf/1/

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

..满足第一个条件abcd-但无法满足第二个条件(否定-ed).

预期输出是abcd-eest-xyz-bnn从第二个输入选项。任何帮助将非常感激。多谢。


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

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

Demo https://regex101.com/r/TxOK08/1.

重要部分的细分:

(?:                 # 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.

或者简单来说:

匹配一个连字符,后跟:

  • 只有字母“e”。Or..
  • a word* not starting with 'e'. Or..
  • 以“e”开头,后面不跟“d”的单词。

*A "word" here means a string of word characters as defined in regex.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 re2 正则表达式否定字符串模式? 的相关文章

随机推荐