while ( $line =~ / ( [^\[]* ) (?: \[ ( (?:link|email|pdf) [^\]]* ) \] )? /xg ) { my $txt = $1; my $link = $2; if ($link){ my ($type, $address, $txt) = split(/\|/, $link); # more stuff } }