user3277752 user3277752 - 15 days ago 5
Perl Question

Regex Matching Square Brackets

I'm parsing a log file and am stuck on trying to write a regex for the following token

sshd[7623]:


I can match the sshd string, but when matching the opening square bracket, perl just throws an error about missing the closing square bracket.

If I try matching both at the same time, as below, I don't catch either.

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


But neither have worked. What is a proper way to match?

Answer

This captures the word before the bracket and the number inside the bracket:

use warnings;
use strict;

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

__END__

word=sshd number=7623

perldoc perlre

Comments