mad2code has asked for the wisdom of the Perl Monks concerning the following question:

I have a perl variable $webpage which contains a multi-line string ie an index.htm page. I would like to load into another variable $ip just the ip address which is contained within the variable $webpage. I only know how to strip things out of a string such as $webpage =~ s/something to remove//g; However in this case I want to do the opposite ie match a short substring in $webpage to the pattern of '[-0-9].[0-9]/[0-9].[0-9]'; Any ideas?

Replies are listed 'Best First'.
Re: How to print a substring using regex
by ikegami (Patriarch) on Sep 29, 2006 at 04:10 UTC

    Two common patterns:

    my ($substr) = $var =~ /(pattern)/; print $substr, "\n" if defined $substr;
    if ($var =~ /(pattern)/) { print "$1\n"; }

    Don't forget to put the parens around what you want to capture.

    Update: Two common patterns for multiple matches:

    my @substrs = $var =~ /(pattern)/g; print "$_\n" foreach @substrs;
    while ($var =~ /(pattern)/g) { print "$1\n"; }
      Thanks for the responses, it worked like a charm.
Re: How to print a substring using regex
by bobf (Monsignor) on Sep 29, 2006 at 04:17 UTC

    To expand on ikegami's answer, take a look at Regexp::Common::net. It contains a pre-built regex pattern that recognizes dotted decimal IP addresses (constructing your own could be tricky). The example given in the synopsis section illustrates how it could be used. See also perlre for information about how to capture matches into variables.

Re: How to print a substring using regex
by Persib (Acolyte) on Sep 29, 2006 at 05:38 UTC
    Hi,

    would like to load into another variable $ip just the ip address which is contained within the variable $webpage

    use NetAddr::IP::Find; $content = "this is valid IP 202.155.22.3"; find_ipaddrs($content, sub { my ($a)= @_; print $a, "\n"; });