user2202426
user2202426

Reputation: 25

How could I make this into a regex

I am trying to make this "ServerLog(07-05-2013@22-07)" into a regex.

my $filename = q{ServerLog((\d+)-(\d+)-(\d+)@(\d+)-(\d+))};

This is what I have but it doesnt work. Any suggestions?

EDIT: Would this work?

my $filename = q{ServerLog\((\d+)-(\d+)-(\d+)@(\d+)-(\d+)\)};
my $log = "<D:\\ServerTools\\Logs\\$filename";
my $ref = tie *FH,"File::Tail",(name=>$log);

Upvotes: 0

Views: 106

Answers (2)

shawnhcorey
shawnhcorey

Reputation: 3601

You should space out complex regex by using the /x switch:

my $server_log_qr = qr{
        ServerLog
        \(
        (\d{2})     # capture month
        \-
        (\d{2})     # capture day
        \-
        (\d{4})     # capture year
        \@
        (\d{2})     # capture hour
        \-
        (\d{2})     # capture minute
        \)
    }msx;

my $example = 'ServerLog(07-05-2013@22-07)';
print "$example\n";

my ( $month, $day, $year, $hour, $minute ) = $example =~ $server_log_qr;
print "month  = $month\n";
print "day    = $day\n";
print "year   = $year\n";
print "hour   = $hour\n";
print "minute = $minute\n";

Upvotes: 0

go-oleg
go-oleg

Reputation: 19480

You need to escape the first and last parentheses with a \ since you want them to match actual parentheses in your string:

/ServerLog\((\d+)-(\d+)-(\d+)@(\d+)-(\d+)\)/

like this:

my $string = 'ServerLog(07-05-2013@22-07)';

if( $string =~ /ServerLog\((\d+)-(\d+)-(\d+)@(\d+)-(\d+)\)/) {
  print "matches";
}

Upvotes: 5

Related Questions