$string = "This is barney rubble and his friends joe rockhead and fred flintstone"; $string =~ /(?=.*fred (\w+))?(?=.*barney (\w+))?(?=.*joe (\w+))?/; $company = $1 . '_' . $2 . '_' . $3 . '_' . 'inc'; print "$company\n" # "flintstone_rubble_rockhead_inc"