use strict; use warnings; use 5.010; my $pat1 = qr |(\d-\d\w{2}\.\w+)|; # eg 3-123.7 2-3cd.e my $pat2 = qr |([A-Z]\d{2}\.\d+)|; # eg A12.34 Z56.78 my $title; while ( ) { chomp; if ( /(.+)(\(.+\))$/ ) { # Better regex for 'title' lines?? $title = "$1$2;"; } else { next unless /$pat1|$pat2/; my @items = grep length, split /$pat1|$pat2/; say $title, splice @items, 0, 2 while @items; } } __DATA__ Titel Text (A12-3) 3-123.7 Just another (small) text 3-123.8 Some more text A12.34 Another item B56.78 Yet another item Another Titel Text (B23-9) Some trash here 12-22a **This is trash*** 1-22a.b Just another text 2-3cd.e Some more text W12.34 Another item Z56.78 Yet another item Z56.78 And another!! Z56.7a And another!!! Some trash