使用正则表达式从具有可变子域的 URL 中提取环境、域和主机名

问题描述 投票:0回答:1

我正在开发一个项目,需要从 URL 中提取特定信息,特别是环境、域和主机名。 URL 具有可变的子域,我很难构建正则表达式模式来捕获所需的组。

链接:https://regex101.com/r/4DhLns/3

我需要帮助制作一个可以有效捕获以下组的正则表达式模式:

  • 第 1 组:环境(例如阶段、质量保证)
  • 第 2 组:主机名(例如, 主机名)
  • 第 3 组:域名(例如 com)

const regex = /.*(?<environment>(qa|stage*)).*\.(?<hostname>\w+)*\.(?<domain>\w+)$/;

function extractInfoFromURL(url) {
    const match = url.match(regex);
    
    if (match) {
        return match.groups;
    } else {
        return null; // URL didn't match the pattern
    }
}

const testUrls = [
    "https://example.test.qa.sub.hostname.com",
    "https://example.test.stage.coonect.hostname.com",
    "https://example.qa.hostname.com",
    "https://example.hostname.com",
    "https://example.stage.hostname.com",
    "https://ops-cert-stage-beta.apps.sub-test.minor.qa.test.sub.hostname.com",
    "https://ops-cert-qa-beta.apps.sub-test.minor.qa.test.sub.hostname.com",
    "https://ops-cert-qa.apps.sub-test.minor.qa.test.sub.hostname.com",
    "https://ops-cert-stage.apps.sub-test.minor.qa.test.sub.hostname.com"
];

testUrls.forEach((url, index) => {
    const result = extractInfoFromURL(url);
    
    if (result) {
        console.log(`Result for URL ${index + 1}:`, result);
    } else {
        console.log(`URL ${url} did not match the pattern.`);
    }
});

这里,问题在于:https://example.hostname.com,这里的 env 应该为空,并且域和主机应该存在。

RexEx101:https://regex101.com/r/aCCWRv/2

javascript regex regex-group
1个回答
0
投票

第一部分

.*?
可以从图案中省略。如果匹配中不能有空格,则
.*?
可能是
\S*?
匹配尽可能少的非空白字符。

指定的组已经是一个组,因此您不必在其中指定另一个单独的捕获组。

如果环境是可选的,那么您可以使用可选的非捕获组,直到“主机名”开始的部分。

前导

\b
是单词边界,用于防止部分单词匹配。

当前您正在使用

\w
,它可能仅限于匹配允许的字符。您可以使用字符类
[...]
指定所有允许的字符来扩展它。

\b(?:(?<environment>qa|stage|dev|preprod)\S*?\.)?(?<hostname>\w+)\.(?<domain>\w+)$

正则表达式演示

const regex = /\b(?:(?<environment>qa|stage|dev|preprod)\S*?\.)?(?<hostname>\w+)\.(?<domain>\w+)$/;

function extractInfoFromURL(url) {
  const match = url.match(regex);

  if (match) {
    return match.groups;
  } else {
    return null; // URL didn't match the pattern
  }
}

const testUrls = [
  "https://example.test.qa.sub.hostname.com",
  "https://example.test.stage.coonect.hostname.com",
  "https://example.qa.hostname.com",
  "https://example.hostname.com",
  "https://example.stage.hostname.com",
  "https://ops-cert-stage-beta.apps.sub-test.minor.qa.test.sub.hostname.com",
  "https://ops-cert-qa-beta.apps.sub-test.minor.qa.test.sub.hostname.com",
  "https://ops-cert-qa.apps.sub-test.minor.qa.test.sub.hostname.com",
  "https://ops-cert-stage.apps.sub-test.minor.qa.test.sub.hostname.com"
];

testUrls.forEach((url, index) => {
  const result = extractInfoFromURL(url);

  if (result) {
    console.log(`Result for URL ${index + 1}:`, result);
  } else {
    console.log(`URL ${url} did not match the pattern.`);
  }
});

© www.soinside.com 2019 - 2024. All rights reserved.