Home > OS >  Regex Extract a capture group based on a parent capture group
Regex Extract a capture group based on a parent capture group

Time:12-09

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:

development [email protected]
production [email protected]
production [email protected]

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

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

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

Is this something that is possible?

CodePudding user response:

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

This will work in Grafana:

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

CodePudding user response:

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".
  • Related