-2

Is it possible to parse both of these urls with a single regex?

First is in this format for a path under project: const str1 = "https://gitlab.com/myproject/my_product/prd/projectbranch/-/tree/master/src/tools/somepath/somename"

Second is in this format for an MR: const str2 = "https://gitlab.com/myproject/my_product/prd/projectbranch/-/merge_requests/20"

Im able to parse the first like this:

const [_, baseUrl, type, branchName, relativePath] = str1.match(/(.*)\/-\/(tree|merge_requests)\/(.+?)(?:\/(.*$))/)

But I couldnt manage to parse the first and second strings in a single regular expression.

Basically I want to do sth like this (This doesnt work):

const [_, baseUrl, type, mergeRequestNumber] = str2.match(/(.*)\/-\/(tree|merge_requests)\/(.+?)(?:\/(.*$))/)

Edit: I want mergeRequestNumberto match 20 in 2nd match without breaking the 1st match.

Machavity
  • 30,841
  • 27
  • 92
  • 100
damdafayton
  • 1,600
  • 2
  • 10
  • 19

1 Answers1

0

If you want to parse any GitLab URL, you will have to check the type to process the tokens correctly.

const GITLAB_PATH = /(.*)\/-\/(tree|merge_requests)\/(\w+)(?:\/(.*$))?/;

const parseGitLabUrl = (url) => {
  const match = new URL(url).pathname.match(GITLAB_PATH);
  if (!match) return null;
  let [_, basePath, type, ...rest] = match;
  switch (type) {
    case 'merge_requests':
      let mergeRequestNumber;
      [mergeRequestNumber] = rest;
      return { basePath, type, mergeRequestNumber };
    case 'tree':
      let branchName, relativePath;
      [branchName, relativePath] = rest;
      return { basePath, type, branchName, relativePath };
    default:
      return null;
  }
};

const
  str1 = 'https://gitlab.com/myproject/my_product/prd/projectbranch/-/tree/master/src/tools/somepath/somename',
  str2 = 'https://gitlab.com/myproject/my_product/prd/projectbranch/-/merge_requests/20';

console.log(parseGitLabUrl(str1));
console.log(parseGitLabUrl(str2));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • There is no second regex. The idea is to do them all in the same regex. I know how to parse it. I am asking if its possible to get those two results with a single regex. – damdafayton Jan 27 '23 at 19:06
  • Ive checked your solution and its what I was doing already. This question is not about the git URL or how to match them. Its about matching two patterns which I presented in ONE SINGLE regex. And the solution has already been given by someone. But moderators removed those comments. If they wont make it visible again Ill post here the correct answer. – damdafayton Jan 30 '23 at 13:12