0

I have a variable that holds some 100 lines in it. I need to print the lines where there is a url.

$string = "this is just a test line 1
this is a test line 2
http://somelink1
this is line 4
http://link2
...
...

I need to print only the url links.

How to print all the lines matching pattern from $string. Tried the below code.

my $resu =~ /(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?/, $string;
print $resu;
  • 1
    Please show what you have tried. – Jens Sep 30 '14 at 18:45
  • 3
    If you did not read all your input into a scalar in one long string, it would be a simple matter to loop over the input line by line and print the desired lines. This is a bit of an XY-problem. – TLP Sep 30 '14 at 18:49
  • Although it has been closed with a related but not duplicate question, I think the piece you are looking for in the regex is the flags: mgc (multi-line, global, don't reset the position). Then loop through the match in a while loop. – OtherDevOpsGene Sep 30 '14 at 18:59

1 Answers1

1

You need to use the /g Modifier to match multiple lines:

use strict;
use warnings;

my $string = <<'END_STR';
this is just a test line 1
this is a test line 2
http://somelink1
this is line 4
http://link2
...
...
END_STR

while ($string =~ m{(.*http://.*)}g) {
    print "$1\n";
}

Outputs:

http://somelink1
http://link2

However, if you're pulling in this data from a file, you'd be better off just doing line by line file reading:

while (<$fh>) {
    print if m{(.*http://.*)}g;
}
Miller
  • 34,962
  • 4
  • 39
  • 60