XML technologies / Regular expressions / Practical regex techniques / HTML examples / Dissecting an HTTP URL
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
We now have a URL. We test whether it is an HTTP URL and, if so, split it into server name, port number and path. Knowing that this is some kind of URL makes the task much easier than having to identify a URL in arbitrary text. That is much harder; we will tackle it later in this chapter.
Given a URL, we need only identify its parts. The server or hostname is everything after ˹^http://˼ but before the next slash, if any; the path is everything after it: ˹^http://([^/]+)(/.*)?$˼
We forgot the port number. It is optional, precedes the slash and is separated from the server name by a colon: ˹^http://([^/:]+(:(\d+))?)(/.*)?$˼
The following Perl program splits an HTTP URL using this recipe:
if ($url =~ m{^http://([^/:]+(:(\d+))?)(/.*)?$}i)
{
my $host = $1;
my $port = $3 || 80; # $3, falls definiert und nicht leer, sonst 80.
my $pfad = $4 || "/"; # $4, falls definiert und nicht leer, sonst "/".
print "Host: $host\n";
print "Port: $port\n";
print "Pfad: $pfad\n";
} else {
print "Keine HTTP-URL\n";
}
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln
back to top