my $alpha = 'a-zA-Z'; my $alphanum = $alpha.'\d'; my $any = $alphanum.'-'; my $label = qr/ (?:[$alpha]| # start with a letter \d[$any]*[$alpha]+) # or a number if there's a letter elsewhere (?: [$any]* # followed by more stuff maybe [$alphanum] # as long as it doesn't end with a - )? /x; $is_valid = /^(?:$label\.)*$label$/;