$ret = $1 if $g =~ /\n\s*\n((?m:^#.*\n)+)$id/; #### /\n\s*\n # This matches your blank line between comments. ( # Capture into $1. (?m: # Don't capture, but match this group as multiline. Which means match '^' and '$' # at the beginning or end of any line in the string. ^# # Match the comment delimiter at the start of a line. .*\n # Match everything up to, and including, the newline at the end of a line. )+ # Match this group one or more times. ) # End of $1 capture. $id # This is the key you're looking for. /x