Aaron
Aaron

Reputation: 601

Regex Extract a capture group based on a parent capture group

I'm trying to format a drop down variable in Grafana in which the values are structured email addresses that I need to set a portion to the named capture group and place the entire email address in the named capture group . The general details of what I'm trying to do is explained on the Grafana Support page. What I'm looking to do is take the values in a variable query and modify them in the regex area to accomplish the following.

With the query result values of:

[email protected]
[email protected]
[email protected]

I would like the regex to produce two named capture groups text and value.

<text>    |     <value>
info      |     [email protected]
errors    |     [email protected]
warnings  |     [email protected]

The regex (\S+\+)?(?<text>\S+)@.*|(?<value>.*) only seems to set the <text> capture group.

Is this something that is possible?

Upvotes: 2

Views: 4471

Answers (3)

Matthias
Matthias

Reputation: 4000

If you're using Loki, you have to use LogQL instead of Prometheus QL as can be seen here, e.g.

{job="security"}
    != "grafana_com"
    |= "session opened"
    != "sudo: "
    |regexp "(^(?P<user>\\S+ {1,2}){11})"
    | line_format "USER = {{.user}}"

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627600

You can use

(?<value>[^@\s]+\+(?<text>[^@\s+]*)@.*)

See the regex demo.

Details:

  • (?<value> - Group "value" start:
    • [^@\s]+ - one or more chars other than @ and whitespace
    • \+ - a literal + char (needs escaping, or it would be a quantifier)
    • (?<text> - Group "text" start:
      • [^@\s+]* - zero or more chars other than @, whitespace and +
    • ) - end of Group "text"
  • @ - a @ char
  • .* - any zero or more chars other than line break chars as many as possible
  • ) - end of Group "value".

Upvotes: 2

dnnshssm
dnnshssm

Reputation: 1305

As @Barmar pointed out in the comments, you want nested groups instead of alternatives.

This will work in Grafana:

/(?<value>\S+\+(?<text>.*)@.*)/

Upvotes: 2

Related Questions