开发者

Regex Help - Directory from a url

开发者 https://www.devze.com 2023-03-13 01:57 出处:网络
I ha开发者_Python百科ve the urls like the following. <a href=\"http://cdn1.xyz.com/testone/2010/a.jpg\">

I ha开发者_Python百科ve the urls like the following.

<a href="http://cdn1.xyz.com/testone/2010/a.jpg">
<a href="http://cdn2.xyz.com/testtwo/2010/a.jpg">

I want to extract the first part of the url. For ex: http://cdn1.xyz.com/testone or http://cdn2.xyz.com/testtwo. What is the regular expression which matches that format.

Thank you.


If you need to pull the links out of HTML, use something like HTML::SimpleLinkExtor to handle that part.

URLs are subtly complicated things and getting more complicated. The regex you use will inevitably be wrong. You can use the URI module to parse the URL and then modify it.

use URI;
my $uri = URI->new($url_string);

Now that we have the $uri as an object we can get just the path part and change that to chop off anything we don't want.

# Get the path already split into pieces
my @path = $uri->path_segments;

# Put just the first bit back, also clear the query 
$uri->path_query($path[0]);

# clear any "#foo" it might have
$uri->fragment(undef);

And now $uri is what you want. Its string overloaded, so you can just use $uri as a string.


if ($string =~ m{([^:]+://[^/]+/[^/]+)}) {
  print $1;
} else {
  print 'no match';
}

Can also try this.


Not too good but works well

$url='<a href="http://cdn1.xyz.com/testone/2010/a.jpg">';
$url =~ m|(\w+)://([^/:]+)(:\d+)?/(.*)|;
$aa=$4;
($aa)=split('\/',$aa);
$wanted=$1.'://'.$2.'/'.$aa;
print $wanted;

Pints http://cdn1.xyz.com/testone


Try:

$url =~ m{([^:]*://.*?\.[a-z]*?/[^/]*)/.*};

I might suggest looking for regexp modules that match on URLs. It's a common enough and sometimes difficult task that some packages out there probably do a really good job with. If your needs are really simple and you can guarantee url simplicity though I wouldn't bother.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号