#!/usr/bin/perl -w use strict; while( my $string=) { my( $domain)= ($string=~ m{(?:^|\.) # the beginning of the string or . ([^.]*) # anything but . (and store it in $1) \.com # .com (?:\/|$) # a / or the end of the string }x); print "domain: $domain\n"; } __DATA__ l-12345.in.some.domain.com l-12345.in.some.domain.com/blargh/index.html domain.com/blargh/index.html domain.com domain.com/ l-12345.in.some.domain.com/blargh/foo.com nope.com.domain.com/blargh/foo.com l-12345.in.some.domain.com/blargh/nope.foo.com