in reply to Validate Ip address Regexp

You're correct in believing that your regex says match one to three digits... but more precisely, it says, match one to three digits before a dot... and if the suspect value you feed it has something before the three-digits-before-a-dot it will match that value, too, ignoring, as does your regex, the number(s) (or letters, symbols, etc) which precede the three-digits-before-a-dot.

Illustrating anchors (where ^ means start of string (to the regex) and $ marks end of string:

# 1148750 print "Testing IP Addresses in array, \@ip: \n"; my @ip = ("0123.456.789.654", "a123.456.789.654", "123.456.789.6543", "111.222.333.444") ; for $ip (@ip) { if ( $ip =~ /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/) { print "yes $ip has a match: $1 $2 $3 $4\n"; } else { print "no match\n"; } } print "\n\t whereas, with anchors in the ip, \n"; for $ip(@ip) { if ( $ip =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/) { print "Second regex matches $1 $2 $3 $4\n"; } else { print "no match in $ip \n"; } } =head execution results: Testing IP Addresses in array, @ip: yes 0123.456.789.654 has a match: 123 456 789 654 yes a123.456.789.654 has a match: 123 456 789 654 yes 123.456.789.6543 has a match: 123 456 789 654 yes 111.222.333.444 has a match: 111 222 333 444 whereas, with anchors in the ip, no match in 0123.456.789.654 no match in a123.456.789.654 no match in 123.456.789.6543 Second regex matches 111 222 333 444 =cut

Two Updates in para 1: s/n/in/ and edited for clarity my explanation of what happens when no anchor is specified.

Replies are listed 'Best First'.
Re^2: Validate Ip address Regexp
by akr8986 (Initiate) on Nov 28, 2015 at 12:24 UTC

    Thanks a ton!! helped me to understand a lot and significance of ^ and $

      Now, and without using or looking at Regexp::Common::net or other such modules or Super Search, write, as an exercise (for it may be better in practice to use multiple regexes and separate tests), a single regex that will accept '255.1.12.123' and reject '256.1.12.123' or '300.1.12.123'. (Think of the alternate ranges (hint) of numbers involved: 0-9, 00-99, 000-199, 200-249, 250-255.) Then write a regex that will extract (or parse) valid IPv4 decimal octet addresses from an arbitrary string:
          'foo255.1.12.123bar1.2.3.4 x 11.2.33.44 y 300.123.12.1z000123.3.2.11111'
      Now you've got something.

      See perlre, perlretut, and perlrequick.


      Give a man a fish:  <%-{-{-{-<