Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

print ip address from string using regex

by flyganji (Initiate)
on Oct 04, 2011 at 15:04 UTC ( #929566=perlquestion: print w/ replies, xml ) Need Help??
flyganji has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, First time writing perl question here. Thank you all for help. I have an assignment to write a few lines of code that would match an IP address from $string and store it in a variable called $ip. $string = "My IP is 10.0.0.2" and the result should be $ip = "10.0.0.2" My trial code was

#!/usr/bin/perl $string = "My IP is 10.0.0.2"; if($string =~/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/{ $ip = $string; } print "$ip\n";

I know this will print out "My IP is 10.0.0.2" but I can't seem to make find a solution to print just IP = 10.0.0.2. thank you all again for any solution.

Comment on print ip address from string using regex
Download Code
Re: print ip address from string using regex
by AR (Friar) on Oct 04, 2011 at 15:23 UTC
      i wanna print ip address class also pls tel me the code like 10.10.10.1 is class a 172.30.2.2 is class b like that
Re: print ip address from string using regex
by roboticus (Canon) on Oct 04, 2011 at 15:28 UTC

    flyganji:

    You need to use a group in your regex to capture the match value, as described in perldoc perlre. For example:

    use strict; use warnings; my $string='foo bar baz bow'; if ($string =~ /bar(.*)bow/) { print "between bar and bow is '$1'\n"; }

    gives me:

    $ perl x.pl between bar and bow is ' baz '

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

    Update: Added quotes in print statement to show that the whitespace is also captured.

      Thank you all for help.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://929566]
Approved by Perlbotics
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2014-07-24 23:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (167 votes), past polls