use strict; my $slurpedfile = q{Blah blah blah blah blah Blah // single line c++ comment more blahs "quoted string with /* " blah blah blah blah /* single line c comment */ blah blah blah /* multi line c style comment */ some more blahs // another single line c++ comment blah blah blah }; my @matches = $slurpedfile =~ m{ ( /\* .*? \*/) | ( \/\/[^\n]*) | " (?: [^"\\]* | \\. )* " | ' (?: [^'\\]* | \\. )* ' | . [^/"']* }xgs; @matches = grep {defined $_} @matches; #get rid of undefs my $linenum = 1; foreach my $match (@matches) { $slurpedfile =~ /\Q$match/; my $before = $`; $slurpedfile = $'; my $matched = $&; $linenum += $before =~ tr/\n/\n/; print "$match\n is on line $linenum\n\n"; $linenum += $match =~ tr/\n/\n/; } __OUTPUT__ // single line c++ comment is on line 2 /* single line c comment */ is on line 4 /* multi line c style comment */ is on line 5 // another single line c++ comment is on line 9 #### comment = ' /* comment */ '; /* comment */