-3

I have few lines of data in a multi line string where few lines are overlapping , But I wanted to match the longest line . Below is the sample data . Is there any regex for this ?

This is one two OK.
This is one two OK one three OK.
This is one two OK one three OK one four OK.
This is one two OK one three OK one four OK one five  OK
...

The O/P should now be

This is one two OK one three OK one four OK one five OK.

If I use quantifiers , it matches all the lines . The input starts from This and ends with OK , But it should match only the longest one . Please suggest me .

Paul Roub
  • 35,100
  • 27
  • 72
  • 83
pr33
  • 1
  • 1
  • 1
    Even if it is possible, you shouldn't. I would just split by newline and count which one is the longest. – HamZa Jan 08 '15 at 00:36
  • 3
    As @HamZa says, you shouldn't think of using a regex for this. There is *no way* to find the longest line except by reading through the entire file and comparing the lengths of the lines. If you *could* do it in a regular expression then it would have to do the same thing, so just code it in Perl. – Borodin Jan 08 '15 at 00:45

1 Answers1

4

No, you should use a simple read loop, like this

use strict;
use warnings;

my ($max_len, $longest);
while (<DATA>) {
  my $len = length;
  ($max_len, $longest) = ($len, $_) unless defined $max_len and $len < $max_len;
}

print $max_len, "\n";
print $longest, "\n";

__DATA__
This is one two OK.
This is one two OK one three OK.
This is one two OK one three OK one four OK.
This is one two OK one three OK one four OK one five  OK
...

output

57
This is one two OK one three OK one four OK one five  OK
Borodin
  • 123,915
  • 9
  • 66
  • 138