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;
3
  • 1
    Please show what you have tried. Commented Sep 30, 2014 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. Commented Sep 30, 2014 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. Commented Sep 30, 2014 at 18:59

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.