我怎么能把它变成一个正则表达式

时间:2013-07-06 02:35:30

标签: regex perl

我想把这个“ServerLog(07-05-2013 @ 22-07)”变成一个正则表达式。

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

这就是我所拥有的,但它不起作用。有什么建议吗?

编辑: 这会有用吗?

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

2 个答案:

答案 0 :(得分:5)

您需要使用\转义第一个和最后一个括号,因为您希望它们与字符串中的实际括号匹配:

/ServerLog\((\d+)-(\d+)-(\d+)@(\d+)-(\d+)\)/
像这样:

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

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

答案 1 :(得分:0)

您应该使用/ x开关来填充复杂的正则表达式:

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";