代码之家  ›  专栏  ›  技术社区  ›  Kermit

通过捕获组隔离URL路径

  •  0
  • Kermit  · 技术社区  · 7 年前

    有没有可能 n 捕获组?

    例如,

    http://www.example.com/first-path
    http://www.example.com/first-path/second-path
    http://www.example.com/first-path/second-path/third-path
    http://www.example.com/something.html
    http://www.example.com/first-path?id=5
    

    我想抓住 first-path 作为第1组, second-path 作为第2组,以及 third-path 作为第3组使用 http:\/\/(.*)\/(?!.*\/$)(.*) 但它不会分割这些段。

    没有使用特定的编程语言。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Nick SamSmith1986    7 年前

    如果您使用的是PHP,那么可以这样做。第一个拆分移除了前导 http://www.example.com/ 然后第二部分将这些值围绕 / :

    $urls = array('http://www.example.com/first-path',
    'http://www.example.com/first-path/second-path',
    'http://www.example.com/first-path/second-path/third-path',
    'http://www.example.com/something.html',
    'http://www.example.com/first-path?id=5');
    
    foreach ($urls as $url) {
        $tail = preg_split('#https?://[^/]+/#', $url, -1, PREG_SPLIT_NO_EMPTY)[0];
        $paths = preg_split('#/#', $tail);
        print_r($paths);
    }
    

    输出:

    Array
    (
        [0] => first-path
    )
    Array
    (
        [0] => first-path
        [1] => second-path
    )
    Array
    (
        [0] => first-path
        [1] => second-path
        [2] => third-path
    )
    Array
    (
        [0] => something.html
    )
    Array
    (
        [0] => first-path?id=5
    )
    

    在javascript中也可以做类似的事情:

    let urls = ['http://www.example.com/first-path',
    'http://www.example.com/first-path/second-path',
    'http://www.example.com/first-path/second-path/third-path',
    'http://www.example.com/something.html',
    'http://www.example.com/first-path?id=5'];
    console.log(urls.map(s => s.split(/https?:\/\/[^\/]+\//)[1].split(/\//)))
    

    输出:

    Array(5) […]    ​
      0: Array [ "first-path" ]
      1: Array [ "first-path", "second-path" ]
      2: Array(3) [ "first-path", "second-path", "third-path" ]
      3: Array [ "something.html" ]
      4: Array [ "first-path?id=5" ]