pyramid13
pyramid13

Reputation: 286

A regex query in Grafana

I have this project name in Jenkins:

dir1/dir2/dir3/projectname

now, I want to extract and save each dir [dir1,dir2,dir3] to a different variable also project name. e.g: var1: dir1, var2: dir2, var3: dir3,projectname: projectname I used a lot of regexes but sadly I can't yet. my last effort is:

/(.*)//

But it does not work properly.

Upvotes: 0

Views: 5514

Answers (1)

Patrick Janser
Patrick Janser

Reputation: 4319

If the number of directories is fixed then you could use this regex:

(?<var1>[^\/]+)\/(?<var2>[^\/]+)\/(?<var3>[^\/]+)\/(?<projectname>[^\/]+)

You can test it here: https://regex101.com/r/neV5UU/1/

The concept is to use named groups with the (?<groupname> ) syntax. I prefer searching for any char except the slash with the pattern [^\/] (slash has to be escaped as it is used to start and finish the regex) instead of .* which matches anything.

Example of it running in JavaScript:

const regex = /(?<var1>[^\/]+)\/(?<var2>[^\/]+)\/(?<var3>[^\/]+)\/(?<projectname>[^\/]+)/g;
let output = '';

const paths = [
  'dir1/dir2/dir3/projectname',
  'first/second/third/another-project-name'
];

paths.forEach(path => {
  output += `${path}\n`;
  let m;
  while ((m = regex.exec(path)) !== null) {
    Object.keys(m.groups).forEach((name, index) => {
      output += `${name} = ${m.groups[name]}\n`;
    });
  }
  output += "\n";
});

document.getElementById('output').innerText = output;
<pre id="output"></pre>

But I presume that you'll have a different path length. So in this case you may just use a regex to match items between the slashes and you know that the last one is your project name.

const regex = /[^\/]+/g;
let output = '';

const paths = [
  'dir1/dir2/dir3/projectname',
  'first/second/third/fourth/another-project-name'
];

paths.forEach(path => {
  output += `${path}\n`;
  let m;
  let pieces = [];
  while ((m = regex.exec(path)) !== null) {
    pieces.push(m[0]);
  }
  let projectName = pieces.pop();
  pieces.forEach(piece => {
    output += `path item = ${piece}\n`;
  });
  output += `project name = ${projectName}\n\n`;
});

document.getElementById('output').innerText = output;
<pre id="output"></pre>

Upvotes: 1

Related Questions