首页 文章

正则表达匹配方括号

提问于
浏览
2

我正在解析一个日志文件,但我仍然试图为以下令牌编写正则表达式

sshd[7623]:

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

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

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

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

2 回答

  • 2

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

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

    perldoc perlre

  • 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
    

相关问题