#!/usr/bin/env perl -l use strict; use warnings; my @lines = ( 'Iteration {Applied Field} {Total Energy} Mx', '{blaa blaa blaa}', 'Iteration {Applied Field} {Total Energy} Mx', 'Iteration {Applied Field} A {Total Energy} Mx F G {Third test line}', 'Iteration {Applied Field} {Total Energy} Mx Fx {a} B C D {E F} G', 'Iteration {Applied Field} {Total Energy} {Foo} { a b c d } Mx', ); my $re_hard_to_read = qr/(?>[{]([^}]+)|\s*(?![{}])(\S+))/; my $re_easy_to_read = qr/(?> [{] ( [^}]+ ) | \s* (?! [{}] ) ( \S+ ) )/x; my $re_fully_annotated = qr/ (?> # start non-capturing, non-backtracking, alternation [{] # MATCH: exactly one literal left brace ( # start capture [^}]+ # CAPTURE: one or more of any character except right brace ) # end capture | # - OR - \s* # MATCH: zero or more whitespace (?! # start zero-width negative lookahead assertion [{}] # ASSERT: next character is not left or right brace ) # end zero-width negative lookahead assertion ( # start capture \S+ # CAPTURE: one or more non-whitespace characters ) # end capture ) # end non-capturing, non-backtracking, alternation /x; #my $re = $re_hard_to_read; #my $re = $re_easy_to_read; my $re = $re_fully_annotated; for (@lines) { # Print output heading print join "\n$_\n" => ('-' x 60) x 2; # Array to hold header names my @header_names; # Capture header names push @header_names => $+ while /$re/g; # Output header names print join "\n" => @header_names; } #### ------------------------------------------------------------ Iteration {Applied Field} {Total Energy} Mx ------------------------------------------------------------ Iteration Applied Field Total Energy Mx ------------------------------------------------------------ {blaa blaa blaa} ------------------------------------------------------------ blaa blaa blaa #### ------------------------------------------------------------ Iteration {Applied Field} {Total Energy} Mx ------------------------------------------------------------ Iteration Applied Field Total Energy Mx ------------------------------------------------------------ Iteration {Applied Field} A {Total Energy} Mx F G {Third test line} ------------------------------------------------------------ Iteration Applied Field A Total Energy Mx F G Third test line ------------------------------------------------------------ Iteration {Applied Field} {Total Energy} Mx Fx {a} B C D {E F} G ------------------------------------------------------------ Iteration Applied Field Total Energy Mx Fx a B C D E F G ------------------------------------------------------------ Iteration {Applied Field} {Total Energy} {Foo} { a b c d } Mx ------------------------------------------------------------ Iteration Applied Field Total Energy Foo a b c d Mx