正则表达匹配方形括号

时间:2014-02-07 00:31:39

标签: regex perl

我正在解析一个日志文件而且我一直试图为以下令牌编写正则表达式

sshd[7623]:

我可以匹配sshd字符串,但是当匹配开始方括号时,perl只会抛出关于错过结束方括号的错误。

如果我尝试同时匹配两者,如下所示,我也没有抓到。

$re1='(\\[)(\\d+)(\\])';
$re2='(\\[.*?\\])';

但两者都没有奏效。什么是匹配的正确方法?

2 个答案:

答案 0 :(得分:2)

这会捕获括号前的单词和括号内的数字:

use warnings;
use strict;

if ('sshd[7623]:' =~ /(\w+)\[(\d+)\]:/) {
    print "word=$1 number=$2\n";
}

__END__

word=sshd number=7623

perldoc perlre

答案 1 :(得分:1)

use strict;
use warnings;

while (<DATA>)
{
   if ( /^(\w+)\[(\d+)\]/ )
   {
      print "Found a $1 line with process ID $2\n";
   }
}

__DATA__
sshd[1234]: Foo
imapd[5678]: Bar
sshd[9012]: Baz
pop3d[3456]: Quux