【问题标题】:Extract host + one folder from path从路径中提取主机+一个文件夹
【发布时间】:2011-12-15 21:37:41
【问题描述】:

你能帮我找出一个从 url 中提取的正则表达式吗:

  1. 主机名,当它后面的路径中没有指定文件夹时 例如

    http://jj.com/' -> 'jj.com
    http://jj.com/index.php' -> 'jj.com
    http://jj.com/query?q=http://kk.uk' -> 'jj.com
    
  2. 当路径中至少指定一个文件夹时,主机名+路径中的一个文件夹 例如

    'http://jj.com/site/index.php' -> 'jj.com/site'
    'http://jj.com/site/second/aldldls.html' -> 'jj.com/site'
    

是否可以只用一个正则表达式来做到这一点?

顺便说一句,我将使用 hive 中的 regex_extract 函数,但任何可以做到这一点的正则表达式变体(例如 perl 正则表达式)都将非常有用。

【问题讨论】:

  • 为什么要重新发明轮子? CPAN 上应该有可以处理这个问题的模块。 URI 或许?

标签: regex perl hive


【解决方案1】:
use 5.010;
use URI;

for (
    'http://jj.com/',
    'http://jj.com/index.php',
    'http://jj.com/query?q=http://kk.uk',
    'http://jj.com/site/index.php',
    'http://jj.com/site/second/aldldls.html',
) {
    my $u = URI->new($_);
    say (
        ($u->path_segments)[2]
            ? join q(/), $u->host, ($u->path_segments)[1]
            : $u->host
    );
}

输出

jj.com
jj.com
jj.com
jj.com/site
jj.com/site

【讨论】:

    【解决方案2】:
    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    for (<DATA>) {
        s!^http://([^/]+/([^\?/]+/)?).*!$1!;
        s!/\s*$!!;
        print "$_\n";
    }
    
    __DATA__
    http://jj.com/
    http://jj.com/index.php
    http://jj.com/query?q=http://kk.uk
    http://jj.com/site/index.php
    http://jj.com/site/second/aldldls.html
    

    输出:

    jj.com
    jj.com
    jj.com
    jj.com/site
    jj.com/site
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      相关资源
      最近更新 更多