use strict; use warnings; my $str1 = 'http://hostname.company.com:80//directory/'; my $str2 = 'http://hostname.company.com:80//'; for ( $str1, $str2 ) { my ( $host, $dir ) = m{https?://([^:]+):\d+//(:?([^/]+)/)?}; print "Host: $host, Dir: ", ( defined($dir) ? $dir : 'undefined' ), "\n"; }