【问题标题】:Javascript regular expression to parse git urls [duplicate]用于解析 git url 的 Javascript 正则表达式 [重复]
【发布时间】:2023-01-30 20:51:07
【问题描述】:

是否可以用一个正则表达式解析这两个 url?

首先是项目下路径的这种格式: const str1 = "https://gitlab.com/myproject/my_product/prd/projectbranch/-/tree/master/src/tools/somepath/somename"

第二种是 MR 的这种格式: const str2 = "https://gitlab.com/myproject/my_product/prd/projectbranch/-/merge_requests/20"

我能够像这样解析第一个:

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

但是我无法在单个正则表达式中解析第一个和第二个字符串。

基本上我想这样做(这不起作用):

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

编辑:我希望mergeRequestNumber在第二场比赛中匹配20而不破坏第一场比赛。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    如果你想解析任何GitLab URL,您必须检查 type 才能正确处理令牌。

    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; }

    【讨论】:

    • 没有第二个正则表达式。这个想法是在同一个正则表达式中完成它们。我知道如何解析它。我问是否有可能用一个正则表达式得到这两个结果。
    • @damdafayton 查看我更新的回复。
    猜你喜欢
    • 2012-11-21
    • 2015-12-22
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    相关资源
    最近更新 更多