The regular expression: (?-imsx:s/ ^\w*\K\n(?=\w*\n) | ^.*\..*\K\n(?=.*\.) //mx) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- s/ 's/ ' ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- \w* word characters (a-z, A-Z, 0-9, _) (0 or more times (matching the most amount possible)) ---------------------------------------------------------------------- \K 'K' ---------------------------------------------------------------------- \n '\n' (newline) ---------------------------------------------------------------------- (?= look ahead to see if there is: ---------------------------------------------------------------------- \w* word characters (a-z, A-Z, 0-9, _) (0 or more times (matching the most amount possible)) ---------------------------------------------------------------------- \n '\n' (newline) ---------------------------------------------------------------------- ) end of look-ahead ---------------------------------------------------------------------- ' ' ---------------------------------------------------------------------- | OR ---------------------------------------------------------------------- ' ' ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- .* any character except \n (0 or more times (matching the most amount possible)) ---------------------------------------------------------------------- \. '.' ---------------------------------------------------------------------- .* any character except \n (0 or more times (matching the most amount possible)) ---------------------------------------------------------------------- \K 'K' ---------------------------------------------------------------------- \n '\n' (newline) ---------------------------------------------------------------------- (?= look ahead to see if there is: ---------------------------------------------------------------------- .* any character except \n (0 or more times (matching the most amount possible)) ---------------------------------------------------------------------- \. '.' ---------------------------------------------------------------------- ) end of look-ahead ---------------------------------------------------------------------- //mx ' //mx' ---------------------------------------------------------------------- ) end of grouping ----------------------------------------------------------------------