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

CdV*_*dVr 3 regex re2 grafana prometheus

我使用 google re2正则表达式来查询Grafana 仪表板上的Prometheus 。尝试通过以下 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"}
Run Code Online (Sandbox Code Playgroud)

..经过下面列出的验证

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

不知怎的,这个正则表达式

\bkey="(abcd(?:-\w+)*[^-][^e][^d]\w)"
Run Code Online (Sandbox Code Playgroud)

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

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

Ahm*_*eed 5

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

\bkey="(abcd(?:-e|-(?:[^e\W]|e[^d\W])\w*)*)"
Run Code Online (Sandbox Code Playgroud)

演示

重要部分的细分:

(?:                 # 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.
Run Code Online (Sandbox Code Playgroud)

或者简单来说:

匹配一个连字符,后跟:

  • 只有字母“e”。或者..
  • 一个不以“e”开头的单词* 。或者..
  • 以“e”开头,后面不跟“d”的单词。

*这里的“单词”是指正则表达式中定义的一串单词字符。