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

In my endless search for the perfect regex, I have encountered this problem over and over again.
### Haxor ### #!/usr/bin/perl -w use strict; use warnings; my $flag = 0; my $hacklist = "hack.txt"; my $date = 'Date: '; my $octet = '(\d{1,3}\.){3}\d{1,3}'; open HACK, $hacklist or die "Can't Open $hacklist"; my @hack=<HACK>; close(HACK); foreach (@hack) { if (s/$date//){ print; $flag = 0; } if (/$octet/ and !$flag){ print STDOUT $_; print "\n"; $flag = 1; } }
Simple, parse the dates and octets from the hacklist. Currently I get this:
Thursday, December 13, 2001 07:53 AM Subject: FW: Please disconnect 208.202.183.42 thanks. Monday, December 17, 2001 08:56 AM Subject: FW: Please disconnect 213.14.199.133 thanks.
But how do I print only the octet? Everything else on that line is unecessary. Is there a way to print only the matched pattern, disregarding everything else on the line? Ideal results would be:
Thursday, December 13, 2001 07:53 AM 208.202.183.42 Monday, December 17, 2001 08:56 AM 213.14.199.133
Hopefully I will get 'Mastering Regular Expressions' for Christmas. Happy Holidays!

Replies are listed 'Best First'.
Re: Octet Regex
by joealba (Hermit) on Dec 18, 2001 at 00:32 UTC
    Use a backreference.
    if (!$flag && /($octet)/){ print "$1\n"; }
    From Camel 3, p. 41:
    A pair of parenthesis around a part of a regular expression causes whatever was matched by that part to be remembered for later use.

    $1 is the match from the first set of parenthesis in your regexp, $2 the second, and so on.
Re: Octet Regex
by count0 (Friar) on Dec 18, 2001 at 00:44 UTC
    You should also use the 'qr' operator in this case for quoting your regexp (see perlop, and perlre).

    my $octet = qr!(\d{1,3}\.){3}\d{1,3}!;