Search code examples
regexgrafana

Grafana regex to capture two groups


I have a list of database names to capture in grafana:

  • db1-producion
  • db2-production
  • production-aa-db3-cluster
  • production-aa-db4-cluster

So one group is <name>-<environment>, another group is <environment>-aa-<name>-cluster, but I'd like to exclude the -cluster from the second group.

(.*)-cluster works and filters the -cluster from the second group database names, returning: production-aa-db3 and production-aa-db4

But as soon as I add (\w*-\w*)|(.*)-cluster, to capture the first group, it returns: db1-producion, db2-production and production-aa

The result should be:

  • db1-producion
  • db2-production
  • production-aa-db3
  • production-aa-db4

Any ideas welcome.


Solution

  • Problem in your approach is that Grafana uses first capturing group as a result*, and in expression (\w*-\w*)|(.*)-cluster first group matches first two words delimited by dash. (And even if you'd avoid it matching, you'll get an empty variable, since first group wouldn't contain anything)

    To remove trailing -cluster from your results you can use (.+?)(-cluster)?.

    Here, first group matches anything, but in a lazy way, thus allowing optional -cluster to be matched if it exists in the end of line.

    enter image description here

    I assume that anchors ^ and $ aren't necessary in this case, since Grafana seemingly prefers to match whole input string, but unfortunately I cannot find reference for this behaviour in the documentation.


    * : Unless named group value or text is present