Hi everyone!

I was writing a script to filter ip addresses. And used two (simple and incomplete) regexes:

my $ip4 = "([0-9]{1,3}\.){3}[0-9]{1,3}"; my $ip6 = "([a-f0-9]{4}\:)+?"; my $prefix = "/\d\d";

They aren't (and don't need to be) fully correct. I understand that these regexes match an invalid ips like 999.888.777.666, but the ips I have on the list are ok.

My question resides here:

my $pattern = "^($ip4|$ip6)($prefix)?";

It is intented to catch and ip address, followed or not by a prefix. But the resulting match does not catch the prefix:

open (FILE, "<$some_file") or die "Error: $!\n"; while (<FILE>) { next if !~ m[$pattern]; print "Hey, I found \$1: $1 \$2: $2 \$3: $3\n"; } close FILE;

I don't understand how could one use the groups inside two or three levels into parenthesis.

You see, the $pattern variable looks this ugly:

^(([0-9]{1,3}\.){3}[0-9]{1,3}|([a-f0-9]{4}\:)+?)(/\d\d)?

Considering this situation, how the matches are set into $1, $2... variables?

Is there a way to set the ip address into $1 and the $prefix into $2 ?

If possible, I'd like to use $ip4 instead of:

"[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"


### Update ###

There was a little problem about my english, sorry about that. Where I typed 'mask' I wanted to mean 'prefix' (the '/\d\d' part of an ip address). Maybe this is what Kenosis asked (if I understand the question).


In reply to Parenthesis grouping into regexes. by aramisf

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.